Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update NeuroKit2 skill for current APIs

Timothy Kassisddcd380f51e7
diff --git a/skills/neurokit2/SKILL.md b/skills/neurokit2/SKILL.md
index 6ae3d0d3..d2c93c8a 100644
--- a/skills/neurokit2/SKILL.md
+++ b/skills/neurokit2/SKILL.md
@@ -1,353 +1,323 @@
---
name: neurokit2
-description: Comprehensive biosignal processing toolkit for analyzing physiological data including ECG, EEG, EDA, RSP, PPG, EMG, and EOG signals. Use this skill when processing cardiovascular signals, brain activity, electrodermal responses, respiratory patterns, muscle activity, or eye movements. Applicable for heart rate variability analysis, event-related potentials, complexity measures, autonomic nervous system assessment, psychophysiology research, and multi-modal physiological signal integration.
-license: MIT license
-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+description: Use NeuroKit2 to build or audit reproducible research workflows for physiological time-series preprocessing, event/interval analysis, multimodal alignment, variability, and complexity. Trigger when code imports neurokit2 or needs its current APIs, schemas, and method-aware validation—not for diagnosis or device validation.
+license: MIT
+compatibility: Python 3.10+ and uv; pinned workflows use NeuroKit2 0.2.13. Core processing needs NumPy, SciPy, pandas, scikit-learn, matplotlib, PyWavelets, requests, and setuptools; selected EEG, cvxEDA, plotting, file-format, and RQA features need separately locked optional packages.
+allowed-tools: Read, Write, Edit, Bash, Glob
+metadata:
+ version: "1.1"
+ skill-author: K-Dense Inc.
---
# NeuroKit2
-## Overview
+## Scope and evidence cutoff
-NeuroKit2 is a comprehensive Python toolkit for processing and analyzing physiological signals (biosignals). Use this skill to process cardiovascular, neural, autonomic, respiratory, and muscular signals for psychophysiology research, clinical applications, and human-computer interaction studies.
+Use this skill for method-aware, reproducible biosignal research with NeuroKit2. The
+snapshot was checked on **2026-07-23** against:
-## When to Use This Skill
+- stable PyPI **0.2.13**, released 2026-03-02;
+- Python metadata (`>=3.10`; classifiers 3.10–3.14) and wheel dependencies;
+- GitHub release notes/tags, `NEWS.rst`, source at tag `v0.2.13`;
+- official API pages/examples (the live site identified itself as
+ `0.2.13.dev214`); and
+- pinned 0.2.13 runtime signatures and synthetic output schemas.
-Apply this skill when working with:
-- **Cardiac signals**: ECG, PPG, heart rate variability (HRV), pulse analysis
-- **Brain signals**: EEG frequency bands, microstates, complexity, source localization
-- **Autonomic signals**: Electrodermal activity (EDA/GSR), skin conductance responses (SCR)
-- **Respiratory signals**: Breathing rate, respiratory variability (RRV), volume per time
-- **Muscular signals**: EMG amplitude, muscle activation detection
-- **Eye tracking**: EOG, blink detection and analysis
-- **Multi-modal integration**: Processing multiple physiological signals simultaneously
-- **Complexity analysis**: Entropy measures, fractal dimensions, nonlinear dynamics
+The live documentation can be ahead of the stable wheel. Prefer the pinned runtime
+for reproducible work and name both versions if consulting development docs.
-## Core Capabilities
+## Boundary
-### 1. Cardiac Signal Processing (ECG/PPG)
+NeuroKit2 is a research and educational toolbox. Do **not** present its output as:
-Process electrocardiogram and photoplethysmography signals for cardiovascular analysis. See `references/ecg_cardiac.md` for detailed workflows.
+- a diagnosis, treatment recommendation, patient-monitoring decision, or alarm;
+- validation, certification, or regulatory evidence for a medical device; or
+- proof that a physiological construct is measured validly in a new sensor,
+ protocol, environment, population, or disease group.
-**Primary workflows:**
-- ECG processing pipeline: cleaning → R-peak detection → delineation → quality assessment
-- HRV analysis across time, frequency, and nonlinear domains
-- PPG pulse analysis and quality assessment
-- ECG-derived respiration extraction
+Validate acquisition hardware, electrode/optode placement, units, sampling and clock
+accuracy, preprocessing, detector/decomposition method, population, task, and
+outcomes for the intended study. Preserve raw data and an auditable exclusion log.
+Use deidentified local files only; do not place PHI in prompts, logs, examples, or
+bundled fixtures.
-**Key functions:**
-```python
-import neurokit2 as nk
-
-# Complete ECG processing pipeline
-signals, info = nk.ecg_process(ecg_signal, sampling_rate=1000)
+## Reproducible installation
-# Analyze ECG data (event-related or interval-related)
-analysis = nk.ecg_analyze(signals, sampling_rate=1000)
-
-# Comprehensive HRV analysis
-hrv = nk.hrv(peaks, sampling_rate=1000) # Time, frequency, nonlinear domains
+```bash
+uv pip install "neurokit2==0.2.13"
```
-### 2. Heart Rate Variability Analysis
+For optional features, create a uv project, add only the packages actually required at
+reviewed exact versions, and commit/review the resulting `uv.lock` before
+`uv sync --locked`. NeuroKit2 exposes an upstream `full` extra, but this skill
+intentionally does not install that floating transitive set in an automated workflow.
+Optional capabilities can require MNE, cvxopt, Plotly, PyEMD, pyRQA, Pillow, OpenCV,
+or file readers. Record the resolved environment with the analysis. Provision any MNE
+data/template download as an explicit, checksummed study input. Do not install a moving
+development branch for a reproducible study.
-Compute comprehensive HRV metrics from cardiac signals. See `references/hrv.md` for all indices and domain-specific analysis.
+## Required data contract
-**Supported domains:**
-- **Time domain**: SDNN, RMSSD, pNN50, SDSD, and derived metrics
-- **Frequency domain**: ULF, VLF, LF, HF, VHF power and ratios
-- **Nonlinear domain**: Poincaré plot (SD1/SD2), entropy measures, fractal dimensions
-- **Specialized**: Respiratory sinus arrhythmia (RSA), recurrence quantification analysis (RQA)
-
-**Key functions:**
-```python
-# All HRV indices at once
-hrv_indices = nk.hrv(peaks, sampling_rate=1000)
-
-# Domain-specific analysis
-hrv_time = nk.hrv_time(peaks)
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000)
-hrv_nonlinear = nk.hrv_nonlinear(peaks, sampling_rate=1000)
-hrv_rsa = nk.hrv_rsa(peaks, rsp_signal, sampling_rate=1000)
-```
+Before processing, record:
-### 3. Brain Signal Analysis (EEG)
+1. signal identity and sensor/channel configuration;
+2. native sampling rate in Hz and physical unit (or explicitly `arbitrary_unit`);
+3. clock, timestamp origin, drift correction, and synchronization evidence;
+4. polarity/orientation and acquisition-side filters/gain;
+5. missing samples, discontinuities, saturation, flatlines, motion, and annotations;
+6. whether event onsets are zero-based sample indices or seconds;
+7. planned preprocessing order, methods, parameters, exclusions, and outputs; and
+8. participant-level grouping needed to prevent leakage in later statistics.
-Analyze electroencephalography signals for frequency power, complexity, and microstate patterns. See `references/eeg.md` for detailed workflows and MNE integration.
+Never infer units from a column name. Do not silently treat samples as milliseconds,
+volts, microsiemens, or arbitrary units.
-**Primary capabilities:**
-- Frequency band power analysis (Delta, Theta, Alpha, Beta, Gamma)
-- Channel quality assessment and re-referencing
-- Source localization (sLORETA, MNE)
-- Microstate segmentation and transition dynamics
-- Global field power and dissimilarity measures
+## Core workflow
-**Key functions:**
-```python
-# Power analysis across frequency bands
-power = nk.eeg_power(eeg_data, sampling_rate=250, channels=['Fz', 'Cz', 'Pz'])
+### 1. Inspect before transforming
-# Microstate analysis
-microstates = nk.microstates_segment(eeg_data, n_microstates=4, method='kmod')
-static = nk.microstates_static(microstates)
-dynamic = nk.microstates_dynamic(microstates)
+```bash
+python skills/neurokit2/scripts/inspect_signal.py \
+ --input recording.csv --root . --deidentified \
+ --columns ECG,RSP,EDA --time-column time_s \
+ --units ECG=mV,RSP=a.u.,EDA=uS
```
-### 4. Electrodermal Activity (EDA)
+The inspector is bounded and emits no row values or paths. Resolve non-monotonic time,
+duplicate samples, gaps, non-finite values, flat runs, and sampling-rate disagreement
+before filtering.
-Process skin conductance signals for autonomic nervous system assessment. See `references/eda.md` for detailed workflows.
+### 2. Preserve preprocessing order
-**Primary workflows:**
-- Signal decomposition into tonic and phasic components
-- Skin conductance response (SCR) detection and analysis
-- Sympathetic nervous system index calculation
-- Autocorrelation and changepoint detection
+Use this default reasoning order, adapting it to the acquisition and cited method:
-**Key functions:**
-```python
-# Complete EDA processing
-signals, info = nk.eda_process(eda_signal, sampling_rate=100)
+1. preserve immutable raw signal and annotations;
+2. verify time base, units, polarity, clipping, gaps, and artifacts;
+3. segment at long gaps; only interpolate short gaps under a declared policy;
+4. apply modality-specific cleaning at the native sampling rate;
+5. detect peaks/onsets or decompose components;
+6. inspect quality outputs and raw overlays;
+7. correct peaks only with logged categories and sensitivity checks;
+8. derive rates/features;
+9. align continuous modalities on a declared common time grid; and
+10. map event indices to that grid, epoch, baseline, and analyze.
-# Analyze EDA data
-analysis = nk.eda_analyze(signals, sampling_rate=100)
+Do not resample binary markers or peak-index arrays as ordinary continuous signals.
+Map their timestamps to the target grid. Filtering and interpolation can create edge
+artifacts and false precision; retain masks for padded, missing, and rejected regions.
-# Sympathetic nervous system activity
-sympathetic = nk.eda_sympathetic(signals, sampling_rate=100)
-```
+### 3. Treat schemas as runtime observations
-### 5. Respiratory Signal Processing (RSP)
+Return columns depend on NeuroKit2 version, function, method, signal availability, and
+analysis mode. Never claim that one column list is universal.
-Analyze breathing patterns and respiratory variability. See `references/rsp.md` for detailed workflows.
-
-**Primary capabilities:**
-- Respiratory rate calculation and variability analysis
-- Breathing amplitude and symmetry assessment
-- Respiratory volume per time (fMRI applications)
-- Respiratory amplitude variability (RAV)
-
-**Key functions:**
```python
-# Complete RSP processing
-signals, info = nk.rsp_process(rsp_signal, sampling_rate=100)
-
-# Respiratory rate variability
-rrv = nk.rsp_rrv(signals, sampling_rate=100)
-
-# Respiratory volume per time
-rvt = nk.rsp_rvt(signals, sampling_rate=100)
+signals, info = nk.ecg_process(ecg, sampling_rate=250)
+observed_schema = {
+ "columns": list(signals.columns),
+ "info_keys": sorted(info),
+}
```
-### 6. Electromyography (EMG)
-
-Process muscle activity signals for activation detection and amplitude analysis. See `references/emg.md` for workflows.
+Persist the observed schema with package version, method parameters, sampling rate, and
+quality/exclusion summary. Reference files list verified default schemas for 0.2.13,
+not guarantees for every method.
-**Key functions:**
-```python
-# Complete EMG processing
-signals, info = nk.emg_process(emg_signal, sampling_rate=1000)
+## Current patterns
-# Muscle activation detection
-activation = nk.emg_activation(signals, sampling_rate=1000, method='threshold')
-```
+### ECG, corrected peaks, and duration-aware HRV
-### 7. Electrooculography (EOG)
+In stable 0.2.13, `ecg_process()` performs cleaning, R-peak detection with
+`correct_artifacts=True`, rate, default `averageQRS` quality, DWT delineation, and phase.
-Analyze eye movement and blink patterns. See `references/eog.md` for workflows.
-
-**Key functions:**
```python
-# Complete EOG processing
-signals, info = nk.eog_process(eog_signal, sampling_rate=500)
-
-# Extract blink features
-features = nk.eog_features(signals, sampling_rate=500)
+signals, info = nk.ecg_process(ecg, sampling_rate=250, method="neurokit")
+time_hrv = nk.hrv_time(info, sampling_rate=250)
```
-### 8. General Signal Processing
-
-Apply filtering, decomposition, and transformation operations to any signal. See `references/signal_processing.md` for comprehensive utilities.
+Inspect `ECG_R_Peaks_Uncorrected` and `ECG_fixpeaks_*`; a corrected series is not
+automatically a valid NN series. For frequency/nonlinear HRV, enforce metric-specific
+duration and beat-count requirements. Five minutes is the conventional short-term
+reference; ULF is a long-recording measure, and VLF interpretation from short records
+is unsafe. Do not interpret LF/HF as a direct sympathovagal balance. PPG pulse-rate
+variability is not interchangeable with ECG HRV.
-**Key operations:**
-- Filtering (lowpass, highpass, bandpass, bandstop)
-- Decomposition (EMD, SSA, wavelet)
-- Peak detection and correction
-- Power spectral density estimation
-- Signal interpolation and resampling
-- Autocorrelation and synchrony analysis
+Use the bounded pipeline:
-**Key functions:**
-```python
-# Filtering
-filtered = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5, highcut=40)
-
-# Peak detection
-peaks = nk.signal_findpeaks(signal)
-
-# Power spectral density
-psd = nk.signal_psd(signal, sampling_rate=1000)
+```bash
+python skills/neurokit2/scripts/ecg_hrv_pipeline.py \
+ --synthetic --sampling-rate 250 --duration 300 \
+ --domains time,frequency,nonlinear
```
-### 9. Complexity and Entropy Analysis
+### EDA with explicit decomposition
-Compute nonlinear dynamics, fractal dimensions, and information-theoretic measures. See `references/complexity.md` for all available metrics.
+The stable default `eda_process(method="neurokit")` uses high-pass tonic/phasic
+decomposition, not cvxEDA. Choose and report decomposition explicitly:
-**Available measures:**
-- **Entropy**: Shannon, approximate, sample, permutation, spectral, fuzzy, multiscale
-- **Fractal dimensions**: Katz, Higuchi, Petrosian, Sevcik, correlation dimension
-- **Nonlinear dynamics**: Lyapunov exponents, Lempel-Ziv complexity, recurrence quantification
-- **DFA**: Detrended fluctuation analysis, multifractal DFA
-- **Information theory**: Fisher information, mutual information
-
-**Key functions:**
```python
-# Multiple complexity metrics at once
-complexity_indices = nk.complexity(signal, sampling_rate=1000)
-
-# Specific measures
-apen = nk.entropy_approximate(signal)
-dfa = nk.fractal_dfa(signal)
-lyap = nk.complexity_lyapunov(signal, sampling_rate=1000)
+clean = nk.eda_clean(eda, sampling_rate=100, method="neurokit")
+components = nk.eda_phasic(clean, sampling_rate=100, method="highpass")
+markers, info = nk.eda_peaks(
+ components["EDA_Phasic"],
+ sampling_rate=100,
+ method="neurokit",
+ amplitude_min=0.1,
+)
```
-### 10. Event-Related Analysis
+For `neurokit`/`kim2004`, `amplitude_min` is relative to the largest detected response;
+it is not an absolute microsiemens threshold. cvxEDA needs optional `cvxopt`.
-Create epochs around stimulus events and analyze physiological responses. See `references/epochs_events.md` for workflows.
-
-**Primary capabilities:**
-- Epoch creation from event markers
-- Event-related averaging and visualization
-- Baseline correction options
-- Grand average computation with confidence intervals
-
-**Key functions:**
-```python
-# Find events in signal
-events = nk.events_find(trigger_signal, threshold=0.5)
-
-# Create epochs around events
-epochs = nk.epochs_create(signals, events, sampling_rate=1000,
- epochs_start=-0.5, epochs_end=2.0)
-
-# Average across epochs
-grand_average = nk.epochs_average(epochs)
+```bash
+python skills/neurokit2/scripts/eda_pipeline.py \
+ --synthetic --sampling-rate 100 --duration 60 \
+ --phasic-method highpass --peak-method neurokit
```
-### 11. Multi-Signal Integration
+### Events, epochs, and baseline
-Process multiple physiological signals simultaneously with unified output. See `references/bio_module.md` for integration workflows.
+`events_find()` reports zero-based sample onsets; duration/spacing arguments are in
+samples. `epochs_create()` takes epoch limits in seconds.
-**Key functions:**
```python
-# Process multiple signals at once
-bio_signals, bio_info = nk.bio_process(
- ecg=ecg_signal,
- rsp=rsp_signal,
- eda=eda_signal,
- emg=emg_signal,
- sampling_rate=1000
+events = nk.events_find(trigger, threshold=0.5, duration_min=2)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=100,
+ epochs_start=-0.2,
+ epochs_end=0.8,
+ baseline_correction=False,
)
-
-# Analyze all processed signals
-bio_analysis = nk.bio_analyze(bio_signals, sampling_rate=1000)
```
-## Analysis Modes
+Plan sample-exact windows first:
-NeuroKit2 automatically selects between two analysis modes based on data duration:
+```bash
+python skills/neurokit2/scripts/plan_epochs.py \
+ --events 1000,2500,4000 --event-unit samples \
+ --sampling-rate 100 --recording-samples 5000 \
+ --epoch-start -0.2 --epoch-end 0.8 \
+ --baseline-start -0.2 --baseline-end 0
+```
-**Event-related analysis** (< 10 seconds):
-- Analyzes stimulus-locked responses
-- Epoch-based segmentation
-- Suitable for experimental paradigms with discrete trials
+In 0.2.13 the epoch slice is end-exclusive, but the generated floating time index
+includes `epochs_end`. Built-in baseline correction subtracts the epoch mean from its
+start through `t=0`; use manual correction for a narrower prespecified baseline.
+Boundary epochs are padded and can contain NaN. Decide drop/pad/error before analysis.
-**Interval-related analysis** (≥ 10 seconds):
-- Characterizes physiological patterns over extended periods
-- Resting state or continuous activities
-- Suitable for baseline measurements and long-term monitoring
+### RSA and multimodal processing
-Most `*_analyze()` functions automatically choose the appropriate mode.
+`bio_process()` assumes all inputs already share one sampling rate and alignment. It
+does not resample, synchronize, estimate drift, or create nested modality dictionaries;
+its `info` output is flat. Unequal lengths are concatenated by index and can introduce
+NaN. RSA is added only when synchronized ECG and RSP are present.
-## Installation
+Validate a strict local manifest before calling it:
```bash
-uv pip install neurokit2
+python skills/neurokit2/scripts/validate_multimodal.py \
+ --manifest streams.json --root . --deidentified
```
-For development version:
-```bash
-uv pip install https://github.com/neuropsychology/NeuroKit/zipball/dev
-```
-
-## Common Workflows
+After independent modality QC and alignment:
-### Quick Start: ECG Analysis
```python
-import neurokit2 as nk
-
-# Load example data
-ecg = nk.ecg_simulate(duration=60, sampling_rate=1000)
+bio_signals, bio_info = nk.bio_process(
+ ecg=ecg_aligned,
+ rsp=rsp_aligned,
+ eda=eda_aligned,
+ sampling_rate=common_rate,
+)
+rsa_summary = nk.hrv_rsa(
+ bio_signals,
+ bio_signals,
+ rpeaks=bio_info,
+ sampling_rate=common_rate,
+ continuous=False,
+)
+```
-# Process ECG
-signals, info = nk.ecg_process(ecg, sampling_rate=1000)
+Summary RSA is a dictionary; `continuous=True` returns a DataFrame with `RSA_P2T` and
+`RSA_Gates` in the verified default workflow. Co-record respiration and report its
+rate/depth/context; RSA is not a direct, context-free measure of vagal tone.
-# Analyze HRV
-hrv = nk.hrv(info['ECG_R_Peaks'], sampling_rate=1000)
+### Complexity returns values plus metadata
-# Visualize
-nk.ecg_plot(signals, info)
-```
+Most complexity functions in 0.2.13 return `(value, info)`. The convenience function
+also returns two objects:
-### Multi-Modal Analysis
```python
-# Process multiple signals
-bio_signals, bio_info = nk.bio_process(
- ecg=ecg_signal,
- rsp=rsp_signal,
- eda=eda_signal,
- sampling_rate=1000
-)
-
-# Analyze all signals
-results = nk.bio_analyze(bio_signals, sampling_rate=1000)
+features, details = nk.complexity(signal) # default which="makowski2022"
+sampen, sampen_info = nk.entropy_sample(signal)
+dfa, dfa_info = nk.fractal_dfa(signal)
```
-### Event-Related Potential
-```python
-# Find events
-events = nk.events_find(trigger_channel, threshold=0.5)
+The default convenience selection is not “all measures.” Complexity estimates are
+sensitive to length, stationarity, normalization, delay, dimension, tolerance, scale,
+and implementation. Predefine them and run sensitivity/surrogate analyses.
-# Create epochs
-epochs = nk.epochs_create(processed_signals, events,
- sampling_rate=1000,
- epochs_start=-0.5, epochs_end=2.0)
+## Bundled command-line helpers
-# Event-related analysis for each signal type
-ecg_epochs = nk.ecg_eventrelated(epochs)
-eda_epochs = nk.eda_eventrelated(epochs)
-```
+All helpers reject URLs, path traversal, and symlinks; bound bytes/rows/channels; refuse
+overwrite unless `--force`; use lazy scientific imports so `--help` works without
+NeuroKit2; never use pickle; and produce deterministic JSON/CSV. Real-data commands
+require `--deidentified`.
-## References
+| Helper | Purpose |
+|---|---|
+| `scripts/generate_synthetic.py` | Dependency-free deterministic CSV fixtures |
+| `scripts/inspect_signal.py` | Bounded CSV/time/gap/flatline inspection |
+| `scripts/ecg_hrv_pipeline.py` | Pinned ECG, quality, peak-correction, HRV workflow |
+| `scripts/eda_pipeline.py` | Explicit cleaning, decomposition, SCR workflow |
+| `scripts/plan_epochs.py` | Sample-exact event, boundary, baseline planner |
+| `scripts/validate_multimodal.py` | Strict units/rates/clocks/alignment schema validator |
-This skill includes comprehensive reference documentation organized by signal type and analysis method:
+Generate a fixture without exposing participant data:
-- **ecg_cardiac.md**: ECG/PPG processing, R-peak detection, delineation, quality assessment
-- **hrv.md**: Heart rate variability indices across all domains
-- **eeg.md**: EEG analysis, frequency bands, microstates, source localization
-- **eda.md**: Electrodermal activity processing and SCR analysis
-- **rsp.md**: Respiratory signal processing and variability
-- **ppg.md**: Photoplethysmography signal analysis
-- **emg.md**: Electromyography processing and activation detection
-- **eog.md**: Electrooculography and blink analysis
-- **signal_processing.md**: General signal utilities and transformations
-- **complexity.md**: Entropy, fractal, and nonlinear measures
-- **epochs_events.md**: Event-related analysis and epoch creation
-- **bio_module.md**: Multi-signal integration workflows
+```bash
+python skills/neurokit2/scripts/generate_synthetic.py \
+ --output synthetic.csv --root . --duration 30 \
+ --sampling-rate 250 --seed 42
+```
-Load specific reference files as needed using the Read tool to access detailed function documentation and parameters.
+## Security note
-## Additional Resources
+No example or helper uses Python `eval()` or `exec()`. NeuroKit2 names such as
+`eeg_*`, `events_*`, and `*_eventrelated()` are ordinary library calls. If a static
+scanner reports an eval/exec pattern based on a substring, inspect the exact line and
+record it as a scanner false positive only after confirming no dynamic execution exists.
-- Official Documentation: https://neuropsychology.github.io/NeuroKit/
-- GitHub Repository: https://github.com/neuropsychology/NeuroKit
-- Publication: Makowski et al. (2021). NeuroKit2: A Python toolbox for neurophysiological signal processing. Behavior Research Methods. https://doi.org/10.3758/s13428-020-01516-y
+## References
+Read only the files needed for the modality or decision:
+All bundled Markdown paths below are under `references/`; this skill has no
+`templates/` or `assets/` reference paths.
+
+| File | Contents |
+|---|---|
+| `references/signal_processing.md` | Filters, gaps, resampling, peaks, PSD, schemas |
+| `references/epochs_events.md` | Event indexing, epoch boundaries, baselines |
+| `references/ecg_cardiac.md` | ECG process, quality, delineation, peak correction |
+| `references/hrv.md` | HRV/RSA inputs, duration, ectopy, interpretation |
+| `references/eda.md` | Cleaning, decomposition, SCR detection |
+| `references/emg.md` | EMG cleaning, amplitude, activation |
+| `references/eog.md` | EOG polarity, MNE default, blink features |
+| `references/eeg.md` | EEG/MNE helpers, power, QC, microstates |
+| `references/ppg.md` | PPG methods, quality semantics, PRV limitations |
+| `references/rsp.md` | Respiration polarity, rate, RRV/RVT/RAV |
+| `references/bio_module.md` | Multimodal alignment and `bio_*` schemas |
+| `references/complexity.md` | Tuple returns, parameter sensitivity, RQA |
+
+## Primary sources checked 2026-07-23
+
+- [PyPI 0.2.13](https://pypi.org/project/neurokit2/)
+- [Official documentation](https://neuropsychology.github.io/NeuroKit/)
+- [API index](https://neuropsychology.github.io/NeuroKit/functions/index.html)
+- [GitHub releases](https://github.com/neuropsychology/NeuroKit/releases)
+- [Makowski et al. (2021), NeuroKit2](https://doi.org/10.3758/s13428-020-01516-y)
+- [Pham et al. (2021), HRV tutorial](https://doi.org/10.3390/s21123998)
+- [Makowski et al. (2022), complexity comparison](https://doi.org/10.3390/e24081036)
+- [SPR guideline index](https://sprweb.org/guidelines-papers)
+- [Quigley et al. (2024), HR/HRV guidelines](https://doi.org/10.1111/psyp.14604)
diff --git a/skills/neurokit2/references/bio_module.md b/skills/neurokit2/references/bio_module.md
index d5758969..adf3743e 100644
--- a/skills/neurokit2/references/bio_module.md
+++ b/skills/neurokit2/references/bio_module.md
@@ -1,417 +1,244 @@
-# Multi-Signal Integration (Bio Module)
+# Multimodal processing with `bio_process`
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable source/runtime
+and the official Bio API/examples.
-The Bio module provides unified functions for processing and analyzing multiple physiological signals simultaneously. It acts as a wrapper that coordinates signal-specific processing functions and enables integrated multi-modal analysis.
+## What `bio_process()` does—and does not do
-## Multi-Signal Processing
+Stable signature:
-### bio_process()
-
-Process multiple physiological signals simultaneously with a single function call.
-
-```python
-bio_signals, bio_info = nk.bio_process(ecg=None, rsp=None, eda=None, emg=None,
- ppg=None, eog=None, sampling_rate=1000)
-```
-
-**Parameters:**
-- `ecg`: ECG signal array (optional)
-- `rsp`: Respiratory signal array (optional)
-- `eda`: EDA signal array (optional)
-- `emg`: EMG signal array (optional)
-- `ppg`: PPG signal array (optional)
-- `eog`: EOG signal array (optional)
-- `sampling_rate`: Sampling rate in Hz (must be consistent across signals or specify per signal)
-
-**Returns:**
-- `bio_signals`: Unified DataFrame containing all processed signals with columns:
- - Signal-specific features (e.g., `ECG_Clean`, `ECG_Rate`, `EDA_Phasic`, `RSP_Rate`)
- - All detected events/peaks
- - Derived measures
-- `bio_info`: Dictionary with signal-specific information (peak locations, parameters)
-
-**Example:**
-```python
-# Process ECG, respiration, and EDA simultaneously
-bio_signals, bio_info = nk.bio_process(
- ecg=ecg_signal,
- rsp=rsp_signal,
- eda=eda_signal,
- sampling_rate=1000
+```text
+bio_process(
+ ecg=None, rsp=None, eda=None, emg=None,
+ ppg=None, eog=None, keep=None, sampling_rate=1000
)
-
-# Access processed signals
-ecg_clean = bio_signals['ECG_Clean']
-rsp_rate = bio_signals['RSP_Rate']
-eda_phasic = bio_signals['EDA_Phasic']
-
-# Access detected peaks
-ecg_peaks = bio_info['ECG']['ECG_R_Peaks']
-rsp_peaks = bio_info['RSP']['RSP_Peaks']
```
-**Internal workflow:**
-1. Each signal is processed by its dedicated processing function:
- - `ecg_process()` for ECG
- - `rsp_process()` for respiration
- - `eda_process()` for EDA
- - `emg_process()` for EMG
- - `ppg_process()` for PPG
- - `eog_process()` for EOG
-2. Results are merged into unified DataFrame
-3. Cross-signal features computed (e.g., RSA if both ECG and RSP present)
+It dispatches each non-`None` vector to the modality's `*_process()` function,
+concatenates outputs by pandas index, adds `keep`, and computes continuous RSA when ECG
+and RSP are both present.
-**Advantages:**
-- Simplified API for multi-modal recording
-- Unified time base for all signals
-- Automatic cross-signal feature computation
-- Consistent output format
+It does **not**:
-## Multi-Signal Analysis
+- infer or accept one native sampling rate per modality;
+- synchronize clocks, estimate lag/drift, or align timestamps;
+- automatically resample streams to `sampling_rate`;
+- reject unequal lengths before concatenation;
+- standardize units; or
+- return a nested modality-info structure.
-### bio_analyze()
+Passing ECG at 1000 Hz and EDA at 100 Hz with `sampling_rate=1000` falsely tells the
+EDA processor that its samples are 1000 Hz. Unequal lengths are outer-concatenated by
+index and can introduce NaN. Align first.
-Perform comprehensive analysis on processed multi-modal signals.
+## Flat output schema
```python
-bio_results = nk.bio_analyze(bio_signals, sampling_rate=1000)
-```
-
-**Parameters:**
-- `bio_signals`: DataFrame from `bio_process()` or custom processed signals
-- `sampling_rate`: Sampling rate (Hz)
-
-**Returns:**
-- DataFrame with analysis results for all detected signal types:
- - Interval-related metrics if duration ≥ 10 seconds
- - Event-related metrics if duration < 10 seconds
- - Cross-signal indices (e.g., RSA if ECG + RSP available)
-
-**Computed metrics by signal:**
-- **ECG**: Heart rate statistics, HRV indices (time, frequency, nonlinear domains)
-- **RSP**: Respiratory rate statistics, RRV, amplitude measures
-- **EDA**: SCR count, amplitude, tonic level, sympathetic indices
-- **EMG**: Activation count, amplitude statistics
-- **PPG**: Similar to ECG (heart rate, HRV)
-- **EOG**: Blink count, blink rate
-
-**Cross-signal metrics:**
-- **RSA (Respiratory Sinus Arrhythmia)**: If ECG + RSP present
-- **Cardiorespiratory coupling**: Phase synchronization indices
-- **Multi-modal arousal**: Combined autonomic indices
-
-**Example:**
-```python
-# Analyze processed signals
-results = nk.bio_analyze(bio_signals, sampling_rate=1000)
-
-# Access results
-heart_rate_mean = results['ECG_Rate_Mean']
-hrv_rmssd = results['HRV_RMSSD']
-breathing_rate = results['RSP_Rate_Mean']
-scr_count = results['SCR_Peaks_N']
-rsa_value = results['RSA'] # If both ECG and RSP present
+bio_signals, bio_info = nk.bio_process(
+ ecg=ecg_aligned,
+ rsp=rsp_aligned,
+ eda=eda_aligned,
+ sampling_rate=100,
+)
```
-## Cross-Signal Features
+`bio_signals` is one wide DataFrame. With pinned synthetic ECG+RSP+EDA, it contained
+43 columns:
-When multiple signals are processed together, NeuroKit2 can compute integrated features:
+- 19 ECG raw/clean/rate/quality/peaks/delineation/phase columns;
+- 11 RSP raw/clean/amplitude/rate/RVT/phase/symmetry/extrema columns;
+- 11 EDA raw/clean/tonic/phasic/SCR columns; and
+- `RSA_P2T`, `RSA_Gates`.
-### Respiratory Sinus Arrhythmia (RSA)
-
-Automatically computed when both ECG and respiratory signals are present.
+`bio_info` is one flat dict built with repeated `dict.update()`. The pinned run
+contained prefixed ECG/RSP/SCR keys, method metadata, and one `sampling_rate`; it did
+not support:
```python
-bio_signals, bio_info = nk.bio_process(ecg=ecg, rsp=rsp, sampling_rate=1000)
-results = nk.bio_analyze(bio_signals, sampling_rate=1000)
-
-rsa = results['RSA'] # Automatically included
+bio_info["ECG"]["ECG_R_Peaks"] # wrong for stable 0.2.13
```
-**Computation:**
-- High-frequency HRV modulation by breathing
-- Requires synchronized ECG R-peaks and respiratory signal
-- Methods: Porges-Bohrer or peak-to-trough
-
-**Interpretation:**
-- Higher RSA: greater parasympathetic (vagal) influence
-- Marker of cardiac-respiratory coupling
-- Health indicator and emotion regulation capacity
-
-### ECG-Derived Respiration (EDR)
-
-If respiratory signal unavailable, NeuroKit2 can estimate from ECG:
+Use:
```python
-ecg_signals, ecg_info = nk.ecg_process(ecg, sampling_rate=1000)
-
-# Extract EDR
-edr = nk.ecg_rsp(ecg_signals['ECG_Clean'], sampling_rate=1000)
+rpeaks = bio_info["ECG_R_Peaks"]
+rsp_troughs = bio_info["RSP_Troughs"]
```
-**Use case:**
-- Estimate respiration when direct measurement unavailable
-- Cross-validate respiratory measurements
-
-### Cardio-EDA Integration
-
-Synchronized cardiac and electrodermal activity:
-
-```python
-bio_signals, bio_info = nk.bio_process(ecg=ecg, eda=eda, sampling_rate=1000)
-
-# Both signals available for integrated analysis
-ecg_rate = bio_signals['ECG_Rate']
-eda_phasic = bio_signals['EDA_Phasic']
-
-# Compute correlations or coupling metrics
-correlation = ecg_rate.corr(eda_phasic)
+Output columns depend on provided modalities, methods, optional dependencies, and
+release. Save `list(bio_signals.columns)` and `sorted(bio_info)`.
+
+## Alignment workflow
+
+### 1. Preserve native clocks
+
+For each stream record:
+
+- timestamp origin/time zone or monotonic device time;
+- native rate and observed timestamp intervals;
+- dropped/duplicate/backward samples;
+- clock reset, drift, and synchronization events;
+- sensor latency and acquisition filters; and
+- unit, polarity, and artifact mask.
+
+Do not align only by truncating arrays to equal length.
+
+### 2. Establish synchronization evidence
+
+Prefer:
+
+1. one acquisition system/shared clock;
+2. common hardware trigger captured on each device;
+3. validated timestamps with drift correction; or
+4. a documented manual alignment with uncertainty.
+
+Cross-correlation can support QC when signals share physiology, but a correlation peak
+can be ambiguous and physiologically lagged. It is not a replacement for a clock.
+
+### 3. Process at native rates
+
+Apply modality-specific cleaning, peak detection, decomposition, and quality at the
+correct native rate. Preserve native event/peak timestamps.
+
+### 4. Build a common grid
+
+Choose the target rate from the fastest retained continuous feature and analysis—not
+convenience. Anti-alias downsampling; report interpolation/filter method and edge
+validity. Map discrete peaks/triggers by time, using an explicit rounding/tolerance
+policy; never spline binary markers.
+
+### 5. Validate before `bio_process()`
+
+The bundled validator accepts a strict JSON manifest:
+
+```json
+{
+ "schema_version": "1.0",
+ "streams": [
+ {
+ "name": "ECG",
+ "path": "ecg.csv",
+ "value_column": "ECG",
+ "time_column": "time_s",
+ "sampling_rate_hz": 250,
+ "unit": "mV"
+ },
+ {
+ "name": "RSP",
+ "path": "rsp.csv",
+ "value_column": "RSP",
+ "time_column": "time_s",
+ "sampling_rate_hz": 50,
+ "unit": "a.u."
+ }
+ ],
+ "alignment": {
+ "reference_stream": "ECG",
+ "synchronization": "shared_clock",
+ "max_start_offset_ms": 2,
+ "minimum_overlap_s": 60
+ }
+}
```
-## Practical Workflows
+```bash
+python skills/neurokit2/scripts/validate_multimodal.py \
+ --manifest streams.json --root . --deidentified
+```
-### Complete Multi-Modal Recording Analysis
+The validator reports units, rates, timestamp order/jitter, missingness, starts, common
+overlap, and whether streams can be passed directly to `bio_process()`. It does not
+resample or modify data.
-```python
-import neurokit2 as nk
-import pandas as pd
+## `keep`
-# 1. Load multi-modal physiological data
-ecg = load_ecg() # Your data loading function
-rsp = load_rsp()
-eda = load_eda()
-emg = load_emg()
+`keep` must be a pandas Series or DataFrame and is concatenated after processed
+modalities. It is useful for a pre-aligned trigger or covariate:
-# 2. Process all signals simultaneously
+```python
bio_signals, bio_info = nk.bio_process(
ecg=ecg,
rsp=rsp,
- eda=eda,
- emg=emg,
- sampling_rate=1000
+ keep=aligned[["Trigger"]],
+ sampling_rate=100,
)
+```
-# 3. Visualize processed signals
-import matplotlib.pyplot as plt
-
-fig, axes = plt.subplots(4, 1, figsize=(15, 12), sharex=True)
-
-# ECG
-axes[0].plot(bio_signals.index / 1000, bio_signals['ECG_Clean'])
-axes[0].set_ylabel('ECG')
-axes[0].set_title('Multi-Modal Physiological Recording')
-
-# Respiration
-axes[1].plot(bio_signals.index / 1000, bio_signals['RSP_Clean'])
-axes[1].set_ylabel('Respiration')
+Verify equal index/length first. Do not use `keep` for participant identifiers or PHI.
-# EDA
-axes[2].plot(bio_signals.index / 1000, bio_signals['EDA_Phasic'])
-axes[2].set_ylabel('EDA (Phasic)')
+## EOG and optional dependencies
-# EMG
-axes[3].plot(bio_signals.index / 1000, bio_signals['EMG_Amplitude'])
-axes[3].set_ylabel('EMG Amplitude')
-axes[3].set_xlabel('Time (s)')
+The high-level Bio wrapper calls `eog_process()` without exposing an EOG method.
+Stable EOG peak detection defaults to MNE, which is optional. A core-only environment
+can therefore fail when `eog` is supplied. Process EOG explicitly with a chosen method
+and merge after alignment, or add MNE at a reviewed exact version to the project lock.
-plt.tight_layout()
-plt.show()
+## RSA
-# 4. Analyze all signals
-results = nk.bio_analyze(bio_signals, sampling_rate=1000)
+When both ECG and RSP are present, stable `bio_process()` adds continuous:
-# 5. Extract key metrics
-print("Heart Rate (mean):", results['ECG_Rate_Mean'])
-print("HRV (RMSSD):", results['HRV_RMSSD'])
-print("Breathing Rate:", results['RSP_Rate_Mean'])
-print("SCRs (count):", results['SCR_Peaks_N'])
-print("RSA:", results['RSA'])
+```text
+RSA_P2T, RSA_Gates
```
-### Event-Related Multi-Modal Analysis
+This assumes the arrays already represent synchronized samples at the supplied rate.
+It does not check respiration polarity, sensor lag, clock drift, or R-peak validity.
+For summary RSA:
```python
-# 1. Process signals
-bio_signals, bio_info = nk.bio_process(ecg=ecg, rsp=rsp, eda=eda, sampling_rate=1000)
-
-# 2. Detect events
-events = nk.events_find(trigger_channel, threshold=0.5)
-
-# 3. Create epochs for all signals
-epochs = nk.epochs_create(bio_signals, events, sampling_rate=1000,
- epochs_start=-1.0, epochs_end=10.0,
- event_labels=event_labels,
- event_conditions=event_conditions)
-
-# 4. Signal-specific event-related analysis
-ecg_eventrelated = nk.ecg_eventrelated(epochs)
-rsp_eventrelated = nk.rsp_eventrelated(epochs)
-eda_eventrelated = nk.eda_eventrelated(epochs)
-
-# 5. Merge results
-all_results = pd.merge(ecg_eventrelated, rsp_eventrelated,
- left_index=True, right_index=True)
-all_results = pd.merge(all_results, eda_eventrelated,
- left_index=True, right_index=True)
-
-# 6. Statistical comparison by condition
-all_results['Condition'] = event_conditions
-condition_means = all_results.groupby('Condition').mean()
-```
-
-### Different Sampling Rates
-
-Handle signals with different native sampling rates:
-
-```python
-# ECG at 1000 Hz, EDA at 100 Hz
-bio_signals, bio_info = nk.bio_process(
- ecg=ecg_1000hz,
- eda=eda_100hz,
- sampling_rate=1000 # Target sampling rate
+rsa = nk.hrv_rsa(
+ bio_signals,
+ bio_signals,
+ rpeaks=bio_info,
+ sampling_rate=100,
+ continuous=False,
)
-# EDA will be automatically resampled to 1000 Hz internally
```
-Or process separately and merge:
-
-```python
-# Process at native sampling rates
-ecg_signals, ecg_info = nk.ecg_process(ecg, sampling_rate=1000)
-eda_signals, eda_info = nk.eda_process(eda, sampling_rate=100)
+Report the RSA method/output family, respiration behavior, usable cycles/windows, and
+alignment uncertainty. See `hrv.md`.
-# Resample to common rate
-eda_resampled = nk.signal_resample(eda_signals, sampling_rate=100,
- desired_sampling_rate=1000)
+## `bio_analyze()`
-# Merge manually
-bio_signals = pd.concat([ecg_signals, eda_resampled], axis=1)
+```text
+bio_analyze(
+ data, sampling_rate=1000, method="auto",
+ window_lengths="constant"
+)
```
-## Use Cases and Applications
-
-### Comprehensive Psychophysiology Research
-
-Capture multiple dimensions of physiological arousal:
-
-- **Cardiac**: Orienting, attention, emotional valence
-- **Respiratory**: Arousal, stress, emotion regulation
-- **EDA**: Sympathetic arousal, emotional intensity
-- **EMG**: Muscle tension, facial expression, startle
-
-**Example: Emotional picture viewing**
-- ECG: Heart rate deceleration during picture viewing (attention)
-- EDA: SCRs reflect emotional arousal intensity
-- RSP: Breath-holding or changes reflect emotional engagement
-- Facial EMG: Corrugator (frown), zygomaticus (smile) for valence
-
-### Stress and Relaxation Assessment
-
-Multi-modal markers provide convergent evidence:
-
-- **Increased stress**: ↑ HR, ↓ HRV, ↑ EDA, ↑ respiration rate, ↑ muscle tension
-- **Relaxation**: ↓ HR, ↑ HRV, ↓ EDA, ↓ respiration rate, slow breathing, ↓ muscle tension
-
-**Intervention effectiveness:**
-- Compare multi-modal indices before vs. after intervention
-- Identify which modalities respond to specific techniques
-
-### Clinical Assessment
-
-**Anxiety disorders:**
-- Heightened baseline EDA, HR
-- Exaggerated responses to stressors
-- Reduced HRV, respiratory variability
-
-**Depression:**
-- Altered autonomic balance (↓ HRV)
-- Blunted EDA responses
-- Irregular respiratory patterns
-
-**PTSD:**
-- Hyperarousal (↑ HR, ↑ EDA baseline)
-- Exaggerated startle (EMG)
-- Altered RSA
-
-### Human-Computer Interaction
-
-Unobtrusive user state assessment:
-
-- **Cognitive load**: ↓ HRV, ↑ EDA, suppressed blinks
-- **Frustration**: ↑ HR, ↑ EDA, ↑ muscle tension
-- **Engagement**: Moderate arousal, synchronized responses
-- **Boredom**: Low arousal, irregular patterns
-
-### Athletic Performance and Recovery
-
-Monitor training load and recovery:
-
-- **Resting HRV**: Daily monitoring for overtraining
-- **EDA**: Sympathetic activation and stress
-- **Respiration**: Breathing patterns during exercise/recovery
-- **Multi-modal integration**: Comprehensive recovery assessment
-
-## Advantages of Multi-Modal Recording
-
-**Convergent validity:**
-- Multiple indices converge on same construct (e.g., arousal)
-- More robust than single measure
-
-**Discriminant validity:**
-- Different signals dissociate under certain conditions
-- ECG reflects both sympathetic and parasympathetic
-- EDA reflects primarily sympathetic
-
-**System integration:**
-- Understand whole-body physiological coordination
-- Cross-signal coupling metrics (RSA, coherence)
-
-**Redundancy and robustness:**
-- If one signal quality poor, others available
-- Cross-validate findings across modalities
-
-**Richer interpretation:**
-- HR deceleration + SCR increase = orienting with arousal
-- HR acceleration + no SCR = cardiac response without sympathetic arousal
-
-## Considerations
-
-### Hardware and Synchronization
-
-- **Same device**: Signals inherently synchronized
-- **Different devices**: Requires common trigger/timestamp
- - Use hardware trigger to mark simultaneous events
- - Software alignment based on event markers
- - Verify synchronization quality (cross-correlate redundant signals)
-
-### Signal Quality Across Modalities
-
-- Not all signals may have equal quality
-- Prioritize based on research question
-- Document quality issues per signal
+It detects available column prefixes and joins modality-specific analysis. With
+interval-related data it can add summary RSA. `method="auto"` uses event-related mode
+when mean duration is under 10 seconds; use explicit `event-related` or
+`interval-related` for a prespecified design.
-### Computational Cost
+`window_lengths` can assign different epoch subwindows by modality. Prespecify them;
+choosing each window after seeing effects multiplies researcher degrees of freedom.
-- Processing multiple signals increases computation time
-- Consider processing in batches for large datasets
-- Downsample appropriately to reduce load
+There is no generic “multimodal arousal,” coherence, or cardiorespiratory-coupling
+score automatically produced by this wrapper. Any custom cross-modal statistic needs
+its own synchronization, lag, stationarity, null model, and multiplicity analysis.
-### Analysis Complexity
+## Missingness and statistics
-- More signals = more variables = more statistical comparisons
-- Risk of Type I error (false positives) without correction
-- Use multivariate approaches or pre-registered analyses
+- Keep one validity/artifact mask per modality; complete-case intersection can remove
+ large or condition-dependent periods.
+- Do not replace a poor modality with another and claim the same construct.
+- Summarize quality/exclusions by participant and condition.
+- Split train/test/validation by participant, not rows or epochs.
+- Avoid pseudo-replication from dense samples.
+- Predefine cross-modal features and correct multiplicity.
-### Interpretation
+## Interpretation boundary
-- Avoid over-interpretation of complex multi-modal patterns
-- Ground in physiological theory
-- Replicate findings before strong claims
+Multimodal convergence does not prove a latent state, diagnosis, or causal mechanism.
+Use `bio_*` for research/education only—not patient, worker, driver, athlete, or device
+monitoring and not medical-device validation.
-## References
+## Sources checked 2026-07-23
-- Berntson, G. G., Cacioppo, J. T., & Quigley, K. S. (1993). Respiratory sinus arrhythmia: autonomic origins, physiological mechanisms, and psychophysiological implications. Psychophysiology, 30(2), 183-196.
-- Cacioppo, J. T., Tassinary, L. G., & Berntson, G. (Eds.). (2017). Handbook of psychophysiology (4th ed.). Cambridge University Press.
-- Kreibig, S. D. (2010). Autonomic nervous system activity in emotion: A review. Biological psychology, 84(3), 394-421.
-- Laborde, S., Mosley, E., & Thayer, J. F. (2017). Heart rate variability and cardiac vagal tone in psychophysiological research–recommendations for experiment planning, data analysis, and data reporting. Frontiers in psychology, 8, 213.
+- [Official Bio API](https://neuropsychology.github.io/NeuroKit/functions/bio.html)
+- [Official custom Bio example](https://neuropsychology.github.io/NeuroKit/examples/bio_custom/bio_custom.html)
+- [Stable v0.2.13 `bio_process` source](https://github.com/neuropsychology/NeuroKit/blob/v0.2.13/neurokit2/bio/bio_process.py)
+- [NeuroKit2 main paper](https://doi.org/10.3758/s13428-020-01516-y)
+- [Grossman & Taylor (2007), RSA interpretation](https://doi.org/10.1016/j.biopsycho.2005.11.014)
diff --git a/skills/neurokit2/references/complexity.md b/skills/neurokit2/references/complexity.md
index 70314dbb..9d66d80e 100644
--- a/skills/neurokit2/references/complexity.md
+++ b/skills/neurokit2/references/complexity.md
@@ -1,715 +1,212 @@
-# Complexity and Entropy Analysis
+# Complexity, entropy, fractals, and RQA
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official Complexity API, and the NeuroKit2 complexity comparison paper.
-Complexity measures quantify the irregularity, unpredictability, and multiscale structure of time series signals. NeuroKit2 provides comprehensive entropy, fractal dimension, and nonlinear dynamics measures for assessing physiological signal complexity.
+## Return convention changed from older examples
-## Main Function
-
-### complexity()
-
-Compute multiple complexity metrics simultaneously for exploratory analysis.
-
-```python
-complexity_indices = nk.complexity(signal, sampling_rate=1000, show=False)
-```
-
-**Returns:**
-- DataFrame with numerous complexity measures across categories:
- - Entropy indices
- - Fractal dimensions
- - Nonlinear dynamics measures
- - Information-theoretic metrics
-
-**Use case:**
-- Exploratory analysis to identify relevant measures
-- Comprehensive signal characterization
-- Comparative studies across signals
-
-## Parameter Optimization
-
-Before computing complexity measures, optimal embedding parameters should be determined:
-
-### complexity_delay()
-
-Determine optimal time delay (τ) for phase space reconstruction.
-
-```python
-optimal_tau = nk.complexity_delay(signal, delay_max=100, method='fraser1986', show=False)
-```
-
-**Methods:**
-- `'fraser1986'`: Mutual information first minimum
-- `'theiler1990'`: Autocorrelation first zero crossing
-- `'casdagli1991'`: Cao's method
-
-**Use for:** Embedding delay in entropy, attractor reconstruction
-
-### complexity_dimension()
-
-Determine optimal embedding dimension (m).
-
-```python
-optimal_m = nk.complexity_dimension(signal, delay=None, dimension_max=20,
- method='afn', show=False)
-```
-
-**Methods:**
-- `'afn'`: Average False Nearest Neighbors
-- `'fnn'`: False Nearest Neighbors
-- `'correlation'`: Correlation dimension saturation
-
-**Use for:** Entropy calculations, phase space reconstruction
-
-### complexity_tolerance()
-
-Determine optimal tolerance (r) for entropy measures.
-
-```python
-optimal_r = nk.complexity_tolerance(signal, method='sd', show=False)
-```
-
-**Methods:**
-- `'sd'`: Standard deviation-based (0.1-0.25 × SD typical)
-- `'maxApEn'`: Maximize ApEn
-- `'recurrence'`: Based on recurrence rate
-
-**Use for:** Approximate entropy, sample entropy
-
-### complexity_k()
-
-Determine optimal k parameter for Higuchi fractal dimension.
-
-```python
-optimal_k = nk.complexity_k(signal, k_max=20, show=False)
-```
-
-**Use for:** Higuchi fractal dimension calculation
-
-## Entropy Measures
-
-Entropy quantifies randomness, unpredictability, and information content.
-
-### entropy_shannon()
-
-Shannon entropy - classical information-theoretic measure.
-
-```python
-shannon_entropy = nk.entropy_shannon(signal)
-```
-
-**Interpretation:**
-- Higher: more random, less predictable
-- Lower: more regular, predictable
-- Units: bits (information)
-
-**Use cases:**
-- General randomness assessment
-- Information content
-- Signal irregularity
-
-### entropy_approximate()
-
-Approximate Entropy (ApEn) - regularity of patterns.
-
-```python
-apen = nk.entropy_approximate(signal, delay=1, dimension=2, tolerance='sd')
-```
-
-**Parameters:**
-- `delay`: Time delay (τ)
-- `dimension`: Embedding dimension (m)
-- `tolerance`: Similarity threshold (r)
-
-**Interpretation:**
-- Lower ApEn: more regular, self-similar patterns
-- Higher ApEn: more complex, irregular
-- Sensitive to signal length (≥100-300 points recommended)
-
-**Physiological applications:**
-- HRV: reduced ApEn in heart disease
-- EEG: altered ApEn in neurological disorders
-
-### entropy_sample()
-
-Sample Entropy (SampEn) - improved ApEn.
-
-```python
-sampen = nk.entropy_sample(signal, delay=1, dimension=2, tolerance='sd')
-```
-
-**Advantages over ApEn:**
-- Less dependent on signal length
-- More consistent across recordings
-- No self-matching bias
-
-**Interpretation:**
-- Same as ApEn but more reliable
-- Preferred in most applications
-
-**Typical values:**
-- HRV: 0.5-2.5 (context-dependent)
-- EEG: 0.3-1.5
-
-### entropy_multiscale()
-
-Multiscale Entropy (MSE) - complexity across temporal scales.
-
-```python
-mse = nk.entropy_multiscale(signal, scale=20, dimension=2, tolerance='sd',
- method='MSEn', show=False)
-```
-
-**Methods:**
-- `'MSEn'`: Multiscale Sample Entropy
-- `'MSApEn'`: Multiscale Approximate Entropy
-- `'CMSE'`: Composite Multiscale Entropy
-- `'RCMSE'`: Refined Composite Multiscale Entropy
-
-**Interpretation:**
-- Entropy at different coarse-graining scales
-- Healthy/complex systems: high entropy across multiple scales
-- Diseased/simpler systems: reduced entropy, especially at larger scales
-
-**Use cases:**
-- Distinguish true complexity from randomness
-- White noise: constant across scales
-- Pink noise/complexity: structured variation across scales
-
-### entropy_fuzzy()
-
-Fuzzy Entropy - uses fuzzy membership functions.
-
-```python
-fuzzen = nk.entropy_fuzzy(signal, delay=1, dimension=2, tolerance='sd', r=0.2)
-```
-
-**Advantages:**
-- More stable with noisy signals
-- Fuzzy boundaries for pattern matching
-- Better performance with short signals
-
-### entropy_permutation()
-
-Permutation Entropy - based on ordinal patterns.
-
-```python
-perment = nk.entropy_permutation(signal, delay=1, dimension=3)
-```
-
-**Method:**
-- Encodes signal into ordinal patterns (permutations)
-- Counts pattern frequencies
-- Robust to noise and non-stationarity
-
-**Interpretation:**
-- Lower: more regular ordinal structure
-- Higher: more random ordering
-
-**Use cases:**
-- EEG analysis
-- Anesthesia depth monitoring
-- Fast computation
-
-### entropy_spectral()
-
-Spectral Entropy - based on power spectrum.
+Most stable 0.2.13 complexity functions return:
```python
-spec_ent = nk.entropy_spectral(signal, sampling_rate=1000, bands=None)
+value, info = function(signal, ...)
```
-**Method:**
-- Normalized Shannon entropy of power spectrum
-- Quantifies frequency distribution regularity
-
-**Interpretation:**
-- 0: Single frequency (pure tone)
-- 1: White noise (flat spectrum)
-
-**Use cases:**
-- EEG: spectral distribution changes with states
-- Anesthesia monitoring
-
-### entropy_svd()
-
-Singular Value Decomposition Entropy.
+Examples:
```python
-svd_ent = nk.entropy_svd(signal, delay=1, dimension=2)
+sampen, sampen_info = nk.entropy_sample(
+ signal, delay=1, dimension=2, tolerance="sd"
+)
+dfa, dfa_info = nk.fractal_dfa(signal)
+hfd, hfd_info = nk.fractal_higuchi(signal, k_max=10)
+lyapunov, lyapunov_info = nk.complexity_lyapunov(signal)
+fi, fi_info = nk.fisher_information(signal)
```
-**Method:**
-- SVD on trajectory matrix
-- Entropy of singular value distribution
-
-**Use cases:**
-- Attractor complexity
-- Deterministic vs. stochastic dynamics
+Do not treat the tuple as a scalar. The current public name is
+`fisher_information()`; `information_fisher()` is not exported.
-### entropy_differential()
+Exceptions exist: for example, `mutual_information()` returns a float. Check the
+stable signature and persist runtime type/schema.
-Differential Entropy - continuous analog of Shannon entropy.
+## `complexity()` is a selected panel
```python
-diff_ent = nk.entropy_differential(signal)
+features, details = nk.complexity(
+ signal,
+ which="makowski2022",
+ delay=1,
+ dimension=2,
+ tolerance="sd",
+)
```
-**Use for:** Continuous probability distributions
+The default does not compute “all complexity measures.” The pinned 0.2.13 probe
+returned a one-row DataFrame with 15 columns:
-### Other Entropy Measures
-
-**Tsallis Entropy:**
-```python
-tsallis = nk.entropy_tsallis(signal, q=2)
-```
-- Generalized entropy with parameter q
-- q=1 reduces to Shannon entropy
-
-**Rényi Entropy:**
-```python
-renyi = nk.entropy_renyi(signal, alpha=2)
+```text
+AttEn, BubbEn, CWPEn, Hjorth, LL,
+MFDFA_Asymmetry, MFDFA_Delta, MFDFA_Fluctuation,
+MFDFA_Increment, MFDFA_Max, MFDFA_Mean,
+MFDFA_Peak, MFDFA_Width, MSPEn, SVDEn
```
-- Generalized entropy with parameter α
-**Additional specialized entropies:**
-- `entropy_attention()`: Attention entropy
-- `entropy_grid()`: Grid-based entropy
-- `entropy_increment()`: Increment entropy
-- `entropy_slope()`: Slope entropy
-- `entropy_dispersion()`: Dispersion entropy
-- `entropy_symbolicdynamic()`: Symbolic dynamics entropy
-- `entropy_range()`: Range entropy
-- `entropy_phase()`: Phase entropy
-- `entropy_quadratic()`, `entropy_cumulative_residual()`, `entropy_rate()`: Specialized variants
+The accompanying dict had method-specific details. This panel reflects a published
+empirical comparison and implementation choices; it is not a universal optimum for
+every signal, endpoint, or population.
-## Fractal Dimension Measures
+## Parameter selection
-Fractal dimensions characterize self-similarity and roughness.
+Phase-space/entropy estimates depend on:
-### fractal_katz()
+- delay (`tau`);
+- embedding dimension (`m`);
+- tolerance/radius (`r`);
+- scale/coarse-graining;
+- symbolization/binning;
+- detrending/integration/order;
+- sampling rate and bandwidth; and
+- usable length and stationarity.
-Katz Fractal Dimension - waveform complexity.
+Stable utilities also return metadata:
```python
-kfd = nk.fractal_katz(signal)
+delay, delay_info = nk.complexity_delay(
+ signal, delay_max=100, method="fraser1986", show=False
+)
+dimension, dimension_info = nk.complexity_dimension(
+ signal, delay=delay, dimension_max=10, method="afnn", show=False
+)
+tolerance, tolerance_info = nk.complexity_tolerance(
+ signal,
+ method="maxApEn",
+ delay=delay,
+ dimension=dimension,
+ show=False,
+)
```
-**Interpretation:**
-- 1: straight line
-- >1: increasing roughness and complexity
-- Typical range: 1.0-2.0
+Optimization can return no solution or raise when search bounds are inadequate. Do not
+silently replace failure with an arbitrary default. Predefine the algorithm/search
+range, report failures, and test sensitivity.
-**Advantages:**
-- Simple, fast computation
-- No parameter tuning
+`tolerance="sd"` commonly maps to a fraction of standard deviation, but amplitude
+normalization, outliers, and signal length alter it. One conventional parameter set is
+not method validation.
-### fractal_higuchi()
+## Major stable families
-Higuchi Fractal Dimension - self-similarity.
+### Entropy
-```python
-hfd = nk.fractal_higuchi(signal, k_max=10)
-```
+Available functions include approximate, sample, fuzzy, permutation, spectral,
+multiscale, dispersion, symbolic-dynamic, SVD, Shannon, Rényi, Tsallis, and other
+variants.
-**Method:**
-- Constructs k new time series from original
-- Estimates dimension from length-scale relationship
+Pinned probes confirmed `(value, info)` for:
-**Interpretation:**
-- Higher HFD: more complex, irregular
-- Lower HFD: smoother, more regular
+- `entropy_approximate()`;
+- `entropy_sample()`;
+- `entropy_multiscale()`;
+- `entropy_permutation()`; and
+- `entropy_spectral()`.
-**Use cases:**
-- EEG complexity
-- HRV analysis
-- Epilepsy detection
+Some values are corrected/normalized by default (for example corrected permutation
+entropy). Record every parameter and logarithm base. Entropy values from different
+algorithms/normalizations are not interchangeable.
-### fractal_petrosian()
+### Fractals
-Petrosian Fractal Dimension - rapid estimation.
+Stable functions include Katz, Higuchi, Petrosian, Sevcik, NLD, PSD slope, Hurst,
+correlation dimension, DFA/MFDFA, density, line length, and tMF.
-```python
-pfd = nk.fractal_petrosian(signal)
-```
+`fractal_dfa()` returns `(float, info)` for monofractal mode and can return a
+DataFrame-like multifractal summary. Report scales, overlap, integration, detrending
+order, q values, and fit diagnostics. Do not interpret alpha values without checking
+which regime and preprocessing generated them.
-**Advantages:**
-- Fast computation
-- Direct calculation (no curve fitting)
-
-### fractal_sevcik()
-
-Sevcik Fractal Dimension - normalized waveform complexity.
+### Lyapunov and RQA
```python
-sfd = nk.fractal_sevcik(signal)
-```
+lle, lle_info = nk.complexity_lyapunov(
+ signal,
+ delay=1,
+ dimension=2,
+ method="rosenstein1993",
+ separation="auto",
+)
+rqa, rqa_info = nk.complexity_rqa(
+ signal,
+ dimension=3,
+ delay=1,
+ tolerance="sd",
+ method="python",
+)
+```
+
+The pinned RQA DataFrame had fields such as `RecurrenceRate`, `Determinism`,
+`Laminarity`, `TrappingTime`, line-length/entropy, divergence, and vertical/white-line
+statistics. `rqa_info` included full recurrence and distance matrices, which scale
+quadratically in signal length. Bound input length and memory.
-### fractal_nld()
+A positive estimated Lyapunov exponent does not by itself prove deterministic chaos.
+RQA results depend strongly on embedding, tolerance, norm, Theiler window, line
+thresholds, nonstationarity, and sample size.
+
+## Signal preparation
+
+1. Preserve raw signal and physical unit.
+2. Apply modality-specific artifact/missing-data policy first.
+3. Define the analysis window and usable length.
+4. Decide detrending, filtering, resampling, and standardization before viewing group
+ effects.
+5. Check stationarity or segment according to the estimand.
+6. Compute prespecified measures and diagnostics.
+7. Compare with surrogates/nulls and parameter sensitivity.
+
+Do not apply blanket z-scoring: amplitude-sensitive measures may change, while scale
+invariant measures may not. Report both rationale and implementation.
+
+## Length and comparability
-Normalized Length Density - curve length-based measure.
+There is no universal minimum sample count across complexity measures. Required length
+grows with embedding dimension, delay, scale count, tolerance, and estimator. Multiscale
+entropy loses points at each coarse-graining scale; RQA and correlation dimension can
+be computationally and statistically unstable on short data.
+
+- Use equal-duration/beat-count windows for direct comparisons unless a validated
+ correction is used.
+- Quantify estimate reliability with simulation/resampling.
+- Avoid comparing measures computed at different sample rates or bandwidths without
+ explicit validation.
+- Return missing/unsupported rather than a numerically convenient but invalid value.
-```python
-nld = nk.fractal_nld(signal)
-```
-
-### fractal_psdslope()
+## Interpretation
-Power Spectral Density Slope - frequency-domain fractal measure.
-
-```python
-slope = nk.fractal_psdslope(signal, sampling_rate=1000)
-```
+High entropy can mean noise, not useful complexity. “Healthy complexity,” “complexity
+loss,” consciousness, disease, stress, and aging claims require a prespecified theory,
+validated acquisition/preprocessing, appropriate controls, and independent evidence.
-**Method:**
-- Linear fit to log-log power spectrum
-- Slope β relates to fractal dimension
+Do not use these measures for diagnosis, anesthesia/consciousness monitoring, seizure
+detection, prognosis, or medical-device validation based on this toolbox alone.
-**Interpretation:**
-- β ≈ 0: White noise (random)
-- β ≈ -1: Pink noise (1/f, complex)
-- β ≈ -2: Brown noise (Brownian motion)
-
-### fractal_hurst()
-
-Hurst Exponent - long-range dependence.
-
-```python
-hurst = nk.fractal_hurst(signal, show=False)
-```
-
-**Interpretation:**
-- H < 0.5: Anti-persistent (mean-reverting)
-- H = 0.5: Random walk (white noise)
-- H > 0.5: Persistent (trending, long-memory)
-
-**Use cases:**
-- Assess long-term correlations
-- Financial time series
-- HRV analysis
-
-### fractal_correlation()
-
-Correlation Dimension - attractor dimensionality.
-
-```python
-corr_dim = nk.fractal_correlation(signal, delay=1, dimension=10, radius=64)
-```
-
-**Method:**
-- Grassberger-Procaccia algorithm
-- Estimates dimension of attractor in phase space
-
-**Interpretation:**
-- Low dimension: deterministic, low-dimensional chaos
-- High dimension: high-dimensional chaos or noise
-
-### fractal_dfa()
-
-Detrended Fluctuation Analysis - scaling exponent.
-
-```python
-dfa_alpha = nk.fractal_dfa(signal, multifractal=False, q=2, show=False)
-```
-
-**Interpretation:**
-- α < 0.5: Anti-correlated
-- α = 0.5: Uncorrelated (white noise)
-- α = 1.0: 1/f noise (pink noise, healthy complexity)
-- α = 1.5: Brownian noise
-- α > 1.0: Persistent long-range correlations
-
-**HRV applications:**
-- α1 (short-term, 4-11 beats): Reflects autonomic regulation
-- α2 (long-term, >11 beats): Long-range correlations
-- Reduced α1: Cardiac pathology
-
-### fractal_mfdfa()
-
-Multifractal DFA - multiscale fractal properties.
-
-```python
-mfdfa_results = nk.fractal_mfdfa(signal, q=None, show=False)
-```
-
-**Method:**
-- Extends DFA to multiple q-orders
-- Characterizes multifractal spectrum
-
-**Returns:**
-- Generalized Hurst exponents h(q)
-- Multifractal spectrum f(α)
-- Width indicates multifractality strength
-
-**Use cases:**
-- Detect multifractal structure
-- HRV multifractality in health vs. disease
-- EEG multiscale dynamics
-
-### fractal_tmf()
-
-Multifractal Nonlinearity - deviation from monofractal.
-
-```python
-tmf = nk.fractal_tmf(signal)
-```
-
-**Interpretation:**
-- Quantifies departure from simple scaling
-- Higher: more multifractal structure
-
-### fractal_density()
-
-Density Fractal Dimension.
-
-```python
-density_fd = nk.fractal_density(signal)
-```
-
-### fractal_linelength()
-
-Line Length - total variation measure.
-
-```python
-linelength = nk.fractal_linelength(signal)
-```
-
-**Use case:**
-- Simple complexity proxy
-- EEG seizure detection
-
-## Nonlinear Dynamics
-
-### complexity_lyapunov()
-
-Largest Lyapunov Exponent - chaos and divergence.
-
-```python
-lyap = nk.complexity_lyapunov(signal, delay=None, dimension=None,
- sampling_rate=1000, show=False)
-```
-
-**Interpretation:**
-- λ < 0: Stable fixed point
-- λ = 0: Periodic orbit
-- λ > 0: Chaotic (nearby trajectories diverge exponentially)
-
-**Use cases:**
-- Detect chaos in physiological signals
-- HRV: positive Lyapunov suggests nonlinear dynamics
-- EEG: epilepsy detection (decreased λ before seizure)
-
-### complexity_lempelziv()
-
-Lempel-Ziv Complexity - algorithmic complexity.
-
-```python
-lz = nk.complexity_lempelziv(signal, symbolize='median')
-```
-
-**Method:**
-- Counts number of distinct patterns
-- Coarse-grained measure of randomness
-
-**Interpretation:**
-- Lower: repetitive, predictable patterns
-- Higher: diverse, unpredictable patterns
-
-**Use cases:**
-- EEG: consciousness levels, anesthesia
-- HRV: autonomic complexity
-
-### complexity_rqa()
-
-Recurrence Quantification Analysis - phase space recurrences.
-
-```python
-rqa_indices = nk.complexity_rqa(signal, delay=1, dimension=3, tolerance='sd')
-```
-
-**Metrics:**
-- **Recurrence Rate (RR)**: Percentage of recurrent states
-- **Determinism (DET)**: Percentage of recurrent points in lines
-- **Laminarity (LAM)**: Percentage in vertical structures (laminar states)
-- **Trapping Time (TT)**: Average vertical line length
-- **Longest diagonal/vertical**: System predictability
-- **Entropy (ENTR)**: Shannon entropy of line length distribution
-
-**Interpretation:**
-- High DET: deterministic dynamics
-- High LAM: system trapped in specific states
-- Low RR: random, non-recurrent dynamics
-
-**Use cases:**
-- Detect transitions in system dynamics
-- Physiological state changes
-- Nonlinear time series analysis
-
-### complexity_hjorth()
-
-Hjorth Parameters - time-domain complexity.
-
-```python
-hjorth = nk.complexity_hjorth(signal)
-```
-
-**Metrics:**
-- **Activity**: Variance of signal
-- **Mobility**: Proportion of standard deviation of derivative to signal
-- **Complexity**: Change in mobility with derivative
-
-**Use cases:**
-- EEG feature extraction
-- Seizure detection
-- Signal characterization
-
-### complexity_decorrelation()
-
-Decorrelation Time - memory duration.
-
-```python
-decorr_time = nk.complexity_decorrelation(signal, show=False)
-```
-
-**Interpretation:**
-- Time lag where autocorrelation drops below threshold
-- Shorter: rapid fluctuations, short memory
-- Longer: slow fluctuations, long memory
-
-### complexity_relativeroughness()
-
-Relative Roughness - smoothness measure.
-
-```python
-roughness = nk.complexity_relativeroughness(signal)
-```
-
-## Information Theory
-
-### fisher_information()
-
-Fisher Information - measure of order.
-
-```python
-fisher = nk.fisher_information(signal, delay=1, dimension=2)
-```
-
-**Interpretation:**
-- High: ordered, structured
-- Low: disordered, random
-
-**Use cases:**
-- Combine with Shannon entropy (Fisher-Shannon plane)
-- Characterize system complexity
-
-### fishershannon_information()
-
-Fisher-Shannon Information Product.
-
-```python
-fs = nk.fishershannon_information(signal)
-```
-
-**Method:**
-- Product of Fisher information and Shannon entropy
-- Characterizes order-disorder balance
-
-### mutual_information()
-
-Mutual Information - shared information between variables.
-
-```python
-mi = nk.mutual_information(signal1, signal2, method='knn')
-```
+## Reproducible report
+
+Record:
-**Methods:**
-- `'knn'`: k-nearest neighbors (nonparametric)
-- `'kernel'`: Kernel density estimation
-- `'binning'`: Histogram-based
-
-**Use cases:**
-- Coupling between signals
-- Feature selection
-- Nonlinear dependence
-
-## Practical Considerations
-
-### Signal Length Requirements
-
-| Measure | Minimum Length | Optimal Length |
-|---------|---------------|----------------|
-| Shannon entropy | 50 | 200+ |
-| ApEn, SampEn | 100-300 | 500-1000 |
-| Multiscale entropy | 500 | 1000+ per scale |
-| DFA | 500 | 1000+ |
-| Lyapunov | 1000 | 5000+ |
-| Correlation dimension | 1000 | 5000+ |
-
-### Parameter Selection
-
-**General guidelines:**
-- Use parameter optimization functions first
-- Or use conventional defaults:
- - Delay (τ): 1 for HRV, autocorrelation first minimum for EEG
- - Dimension (m): 2-3 typical
- - Tolerance (r): 0.2 × SD common
-
-**Sensitivity:**
-- Results can be parameter-sensitive
-- Report parameters used
-- Consider sensitivity analysis
-
-### Normalization and Preprocessing
-
-**Standardization:**
-- Many measures sensitive to signal amplitude
-- Z-score normalization often recommended
-- Detrending may be necessary
-
-**Stationarity:**
-- Some measures assume stationarity
-- Check with statistical tests (e.g., ADF test)
-- Segment non-stationary signals
-
-### Interpretation
-
-**Context-dependent:**
-- No universal "good" or "bad" complexity
-- Compare within-subject or between groups
-- Consider physiological context
-
-**Complexity vs. randomness:**
-- Maximum entropy ≠ maximum complexity
-- True complexity: structured variability
-- White noise: high entropy but low complexity (MSE distinguishes)
-
-## Applications
-
-**Cardiovascular:**
-- HRV complexity: reduced in heart disease, aging
-- DFA α1: prognostic marker post-MI
-
-**Neuroscience:**
-- EEG complexity: consciousness, anesthesia depth
-- Entropy: Alzheimer's, epilepsy, sleep stages
-- Permutation entropy: anesthesia monitoring
-
-**Psychology:**
-- Complexity loss in depression, anxiety
-- Increased regularity under stress
-
-**Aging:**
-- "Complexity loss" with aging across systems
-- Reduced multiscale complexity
-
-**Critical transitions:**
-- Complexity changes before state transitions
-- Early warning signals (critical slowing down)
-
-## References
-
-- Pincus, S. M. (1991). Approximate entropy as a measure of system complexity. Proceedings of the National Academy of Sciences, 88(6), 2297-2301.
-- Richman, J. S., & Moorman, J. R. (2000). Physiological time-series analysis using approximate entropy and sample entropy. American Journal of Physiology-Heart and Circulatory Physiology, 278(6), H2039-H2049.
-- Peng, C. K., et al. (1995). Quantification of scaling exponents and crossover phenomena in nonstationary heartbeat time series. Chaos, 5(1), 82-87.
-- Costa, M., Goldberger, A. L., & Peng, C. K. (2005). Multiscale entropy analysis of biological signals. Physical review E, 71(2), 021906.
-- Grassberger, P., & Procaccia, I. (1983). Measuring the strangeness of strange attractors. Physica D: Nonlinear Phenomena, 9(1-2), 189-208.
+- NeuroKit2 version and function return schema;
+- signal type/unit/rate/bandwidth/window/length;
+- exclusions, interpolation, filtering, detrending, resampling, normalization;
+- algorithm, delay, dimension, tolerance, scales/bins/q/order;
+- optimization method/search space and failures;
+- fit/convergence diagnostics and runtime warnings;
+- surrogate/null and sensitivity results; and
+- multiplicity control and participant-level statistical design.
+
+## Sources checked 2026-07-23
+
+- [Official Complexity API](https://neuropsychology.github.io/NeuroKit/functions/complexity.html)
+- [Stable v0.2.13 complexity source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/complexity)
+- [Makowski et al. (2022), empirical comparison using NeuroKit2](https://doi.org/10.3390/e24081036)
+- [Richman & Moorman (2000), sample entropy](https://doi.org/10.1152/ajpheart.2000.278.6.H2039)
+- [Peng et al. (1995), DFA](https://doi.org/10.1063/1.166141)
+- [Costa et al. (2005), multiscale entropy](https://doi.org/10.1103/PhysRevE.71.021906)
diff --git a/skills/neurokit2/references/ecg_cardiac.md b/skills/neurokit2/references/ecg_cardiac.md
index f239ecd1..a90fc804 100644
--- a/skills/neurokit2/references/ecg_cardiac.md
+++ b/skills/neurokit2/references/ecg_cardiac.md
@@ -1,355 +1,193 @@
-# ECG and Cardiac Signal Processing
+# ECG and cardiac processing
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable source/runtime,
+the live ECG API, and current psychophysiology measurement guidance.
-Process electrocardiogram (ECG) and photoplethysmography (PPG) signals for cardiovascular analysis. This module provides comprehensive tools for R-peak detection, waveform delineation, quality assessment, and heart rate analysis.
+## Acquisition contract
-## Main Processing Pipeline
+Record lead/configuration, electrode placement, reference/ground, hardware gain and
+filters, ADC resolution/range, physical unit, native sampling rate, timestamp clock,
+posture/task, medication and relevant population variables, and artifact annotations.
+Do not infer millivolts from a column named `ECG`.
-### ecg_process()
+Sampling must support the intended endpoint. Rate/R-peak timing and P–QRS–T morphology
+have different bandwidth and precision needs. Psychophysiology guidance commonly uses
+at least 125 Hz and regards 500 Hz as conservative for HRV timing, but this is not a
+universal validation threshold. Validate the complete acquisition and detector on
+representative signals; morphology/delineation often uses 250–1000 Hz.
-Complete automated ECG processing pipeline that orchestrates multiple steps.
+## `ecg_process()` in stable 0.2.13
```python
-signals, info = nk.ecg_process(ecg_signal, sampling_rate=1000, method='neurokit')
-```
-
-**Pipeline steps:**
-1. Signal cleaning (noise removal)
-2. R-peak detection
-3. Heart rate calculation
-4. Quality assessment
-5. QRS delineation (P, Q, S, T waves)
-6. Cardiac phase determination
-
-**Returns:**
-- `signals`: DataFrame with cleaned ECG, peaks, rate, quality, cardiac phases
-- `info`: Dictionary with R-peak locations and processing parameters
-
-**Common methods:**
-- `'neurokit'` (default): Comprehensive NeuroKit2 pipeline
-- `'biosppy'`: BioSPPy-based processing
-- `'pantompkins1985'`: Pan-Tompkins algorithm
-- `'hamilton2002'`, `'elgendi2010'`, `'engzeemod2012'`: Alternative methods
-
-## Preprocessing Functions
-
-### ecg_clean()
-
-Remove noise from raw ECG signals using method-specific filtering.
-
-```python
-cleaned_ecg = nk.ecg_clean(ecg_signal, sampling_rate=1000, method='neurokit')
-```
-
-**Methods:**
-- `'neurokit'`: High-pass Butterworth filter (0.5 Hz) + powerline filtering
-- `'biosppy'`: FIR filtering between 0.67-45 Hz
-- `'pantompkins1985'`: Band-pass 5-15 Hz + derivative-based
-- `'hamilton2002'`: Band-pass 8-16 Hz
-- `'elgendi2010'`: Band-pass 8-20 Hz
-- `'engzeemod2012'`: FIR band-pass 0.5-40 Hz
-
-**Key parameters:**
-- `powerline`: Remove 50 or 60 Hz powerline noise (default: 50)
-
-### ecg_peaks()
-
-Detect R-peaks in ECG signals with optional artifact correction.
-
-```python
-peaks_dict, info = nk.ecg_peaks(cleaned_ecg, sampling_rate=1000, method='neurokit', correct_artifacts=False)
-```
-
-**Available methods (13+ algorithms):**
-- `'neurokit'`: Hybrid approach optimized for reliability
-- `'pantompkins1985'`: Classic Pan-Tompkins algorithm
-- `'hamilton2002'`: Hamilton's adaptive threshold
-- `'christov2004'`: Christov's adaptive method
-- `'gamboa2008'`: Gamboa's approach
-- `'elgendi2010'`: Elgendi's two moving averages
-- `'engzeemod2012'`: Modified Engelse-Zeelenberg
-- `'kalidas2017'`: XQRS-based
-- `'martinez2004'`, `'rodrigues2021'`, `'koka2022'`, `'promac'`: Advanced methods
-
-**Artifact correction:**
-Set `correct_artifacts=True` to apply Lipponen & Tarvainen (2019) correction:
-- Detects ectopic beats, long/short intervals, missed beats
-- Uses threshold-based detection with configurable parameters
-
-**Returns:**
-- Dictionary with `'ECG_R_Peaks'` key containing peak indices
-
-### ecg_delineate()
-
-Identify P, Q, S, T waves and their onsets/offsets.
-
-```python
-waves, waves_peak = nk.ecg_delineate(cleaned_ecg, rpeaks, sampling_rate=1000, method='dwt')
-```
-
-**Methods:**
-- `'dwt'` (default): Discrete wavelet transform-based detection
-- `'peak'`: Simple peak detection around R-peaks
-- `'cwt'`: Continuous wavelet transform (Martinez et al., 2004)
-
-**Detected components:**
-- P waves: `ECG_P_Peaks`, `ECG_P_Onsets`, `ECG_P_Offsets`
-- Q waves: `ECG_Q_Peaks`
-- S waves: `ECG_S_Peaks`
-- T waves: `ECG_T_Peaks`, `ECG_T_Onsets`, `ECG_T_Offsets`
-- QRS complex: onsets and offsets
-
-**Returns:**
-- `waves`: Dictionary with all wave indices
-- `waves_peak`: Dictionary with peak amplitudes
-
-### ecg_quality()
-
-Assess ECG signal integrity and quality.
-
-```python
-quality = nk.ecg_quality(ecg_signal, rpeaks=None, sampling_rate=1000, method='averageQRS')
-```
-
-**Methods:**
-- `'averageQRS'` (default): Template matching correlation (Zhao & Zhang, 2018)
- - Returns quality scores 0-1 for each heartbeat
- - Threshold: >0.6 = good quality
-- `'zhao2018'`: Multi-index approach using kurtosis, power spectrum distribution
-
-**Use cases:**
-- Identify low-quality signal segments
-- Filter out noisy heartbeats before analysis
-- Validate R-peak detection accuracy
-
-## Analysis Functions
-
-### ecg_analyze()
-
-High-level analysis that automatically selects event-related or interval-related mode.
-
-```python
-analysis = nk.ecg_analyze(signals, sampling_rate=1000, method='auto')
+signals, info = nk.ecg_process(
+ ecg,
+ sampling_rate=250,
+ method="neurokit",
+)
```
-**Mode selection:**
-- Duration < 10 seconds → event-related analysis
-- Duration ≥ 10 seconds → interval-related analysis
+The stable source performs:
-**Returns:**
-DataFrame with cardiac metrics appropriate for the analysis mode.
+1. `signal_sanitize()` (index reset only);
+2. `ecg_clean()` with the selected method;
+3. `ecg_peaks(..., correct_artifacts=True)`;
+4. interpolated rate;
+5. default `ecg_quality(..., method="averageQRS")`;
+6. DWT delineation; and
+7. atrial/ventricular phase.
-### ecg_eventrelated()
+The pinned default probe observed these 19 columns:
-Analyze stimulus-locked ECG epochs for event-related responses.
-
-```python
-results = nk.ecg_eventrelated(epochs)
+```text
+ECG_Raw, ECG_Clean, ECG_Rate, ECG_Quality, ECG_R_Peaks,
+ECG_P_Peaks, ECG_P_Onsets, ECG_P_Offsets, ECG_Q_Peaks,
+ECG_R_Onsets, ECG_R_Offsets, ECG_S_Peaks, ECG_T_Peaks,
+ECG_T_Onsets, ECG_T_Offsets, ECG_Phase_Atrial,
+ECG_Phase_Completion_Atrial, ECG_Phase_Ventricular,
+ECG_Phase_Completion_Ventricular
```
-**Computed metrics:**
-- `ECG_Rate_Baseline`: Mean heart rate before stimulus
-- `ECG_Rate_Min/Max`: Minimum/maximum heart rate during epoch
-- `ECG_Phase_Atrial/Ventricular`: Cardiac phase at stimulus onset
-- Rate dynamics across epoch time windows
+This is a verified default schema, not a universal promise. Persist
+`list(signals.columns)` and `sorted(info)`.
-**Use case:**
-Experimental paradigms with discrete trials (e.g., stimulus presentations, task events).
-
-### ecg_intervalrelated()
-
-Analyze continuous ECG recordings for resting state or extended periods.
-
-```python
-results = nk.ecg_intervalrelated(signals, sampling_rate=1000)
-```
+`info` is a flat dict. In the default pinned run it included corrected and uncorrected
+R-peaks, `ECG_fixpeaks_*` diagnostics, sampling rate, methods, and delineated wave
+indices. It is not nested under an `ECG` key.
-**Computed metrics:**
-- `ECG_Rate_Mean`: Average heart rate over interval
-- Comprehensive HRV metrics (delegates to `hrv()` function)
- - Time domain: SDNN, RMSSD, pNN50, etc.
- - Frequency domain: LF, HF, LF/HF ratio
- - Nonlinear: Poincaré, entropy, fractal measures
+## Cleaning and R-peak methods
-**Minimum duration:**
-- Basic rate: Any duration
-- HRV frequency metrics: ≥60 seconds recommended, 1-5 minutes optimal
+High-level methods documented for `ecg_process()` include `neurokit`,
+`pantompkins1985`, `hamilton2002`, `elgendi2010`, and `engzeemod2012`.
+`ecg_clean()` and lower-level peak detection expose additional methods. A cleaning
+method and detector encode different assumptions; do not select whichever produces
+the expected group effect.
-## Utility Functions
-
-### ecg_rate()
-
-Compute instantaneous heart rate from R-peak intervals.
+For custom control:
```python
-heart_rate = nk.ecg_rate(peaks, sampling_rate=1000, desired_length=None)
+clean = nk.ecg_clean(ecg, sampling_rate=250, method="neurokit")
+markers, peak_info = nk.ecg_peaks(
+ clean,
+ sampling_rate=250,
+ method="neurokit",
+ correct_artifacts=False,
+)
```
-**Method:**
-- Calculates inter-beat intervals (IBIs) between consecutive R-peaks
-- Converts to beats per minute (BPM): 60 / IBI
-- Interpolates to match signal length if `desired_length` specified
+Validate:
-**Returns:**
-- Array of instantaneous heart rate values
+- R-peak precision, false positives, missed beats, and ectopy;
+- performance during motion, changing rate, and low-amplitude QRS;
+- lead polarity and possible inversion;
+- filter edge regions and discontinuities; and
+- failure modes by participant, condition, device, and population.
-### ecg_phase()
+## Peak correction
-Determine atrial and ventricular systole/diastole phases.
+`ecg_process()` always requests Lipponen–Tarvainen correction in 0.2.13. Inspect:
```python
-cardiac_phase = nk.ecg_phase(ecg_cleaned, rpeaks, delineate_info)
+uncorrected = info["ECG_R_Peaks_Uncorrected"]
+corrected = info["ECG_R_Peaks"]
+categories = {
+ key: info.get(f"ECG_fixpeaks_{key}", [])
+ for key in ["ectopic", "missed", "extra", "longshort"]
+}
```
-**Phases computed:**
-- `ECG_Phase_Atrial`: Atrial systole (1) vs. diastole (0)
-- `ECG_Phase_Ventricular`: Ventricular systole (1) vs. diastole (0)
-- `ECG_Phase_Completion_Atrial/Ventricular`: Percentage of phase completion (0-1)
-
-**Use case:**
-- Cardiac-locked stimulus presentation
-- Psychophysiology experiments timing events to cardiac cycle
-
-### ecg_segment()
+Correction can improve a tachogram but can also alter HRV. Report corrected proportions,
+categories, thresholds/method, excluded segments, and sensitivity with uncorrected or
+alternative policies. Do not assume an algorithm can distinguish ectopic from erroneous
+detection without waveform review or appropriate labels.
-Extract individual heartbeats for morphological analysis.
+## ECG quality is method-dependent
```python
-heartbeats = nk.ecg_segment(ecg_cleaned, rpeaks, sampling_rate=1000)
+quality = nk.ecg_quality(
+ clean,
+ rpeaks=peak_info["ECG_R_Peaks"],
+ sampling_rate=250,
+ method="averageQRS",
+)
```
-**Returns:**
-- Dictionary of epochs, each containing one heartbeat
-- Centered on R-peak with configurable pre/post windows
-- Useful for beat-to-beat morphology comparison
-
-### ecg_invert()
-
-Detect and correct inverted ECG signals automatically.
-
-```python
-corrected_ecg, is_inverted = nk.ecg_invert(ecg_signal, sampling_rate=1000)
-```
+Stable options include `averageQRS`, `templatematch`, `zhao2018`,
+`dissimilarity`, and `ho2025`.
-**Method:**
-- Analyzes QRS complex polarity
-- Flips signal if predominantly negative
-- Returns corrected signal and inversion status
+- `averageQRS`: continuous array scaled 0–1 by this implementation.
+- `templatematch`: continuous morphology-template correlation; it is relative to the
+ recording.
+- `zhao2018`: one classification string (`Unacceptable`, `Barely acceptable`, or
+ `Excellent`).
+- `dissimilarity`: direction/scale differs from similarity scores.
+- `ho2025`: beat/interval-oriented quality based on detector agreement.
-### ecg_rsp()
+There is no universal `>0.6` acceptance rule across these methods. A quality output is
+not device validation. Define thresholds on independent labeled data and preserve the
+method name and scale.
-Extract ECG-derived respiration (EDR) as respiratory proxy signal.
+## Delineation return order
```python
-edr_signal = nk.ecg_rsp(ecg_cleaned, sampling_rate=1000, method='vangent2019')
+delineation_signals, waves = nk.ecg_delineate(
+ clean,
+ rpeaks=peak_info["ECG_R_Peaks"],
+ sampling_rate=250,
+ method="dwt",
+)
```
-**Methods:**
-- `'vangent2019'`: Bandpass filtering 0.1-0.4 Hz
-- `'charlton2016'`: Bandpass 0.15-0.4 Hz
-- `'soni2019'`: Bandpass 0.08-0.5 Hz
+The first object is a same-length marker DataFrame; the second is a dict of wave sample
+indices. Stable methods include `peak`, `prominence`, `cwt`, and `dwt`. Missing wave
+indices may be NaN. Validate every wave endpoint needed for an interval/morphology
+claim; R-peak accuracy does not validate P/T delineation.
-**Use case:**
-- Estimate respiration when direct respiratory signal unavailable
-- Multi-modal physiological analysis
+## Phase and event-related analysis
-## Simulation and Visualization
+`ECG_Phase_Atrial` and `ECG_Phase_Ventricular` are binary phase labels;
+completion columns are fractions from 0 to 1. Their validity depends on delineation.
+For cardiac-locked stimuli, characterize trigger latency/jitter independently of
+software phase estimates.
-### ecg_simulate()
-
-Generate synthetic ECG signals for testing and validation.
+`ecg_eventrelated()` and `ecg_intervalrelated()` inspect available columns. Their output
+columns are conditional. Use explicit dispatch and save observed columns:
```python
-synthetic_ecg = nk.ecg_simulate(duration=10, sampling_rate=1000, heart_rate=70, method='ecgsyn', noise=0.01)
+features = nk.ecg_analyze(
+ epochs,
+ sampling_rate=250,
+ method="event-related",
+)
```
-**Methods:**
-- `'ecgsyn'`: Realistic dynamical model (McSharry et al., 2003)
- - Simulates P-QRS-T complex morphology
- - Physiologically plausible waveforms
-- `'simple'`: Faster wavelet-based approximation
- - Gaussian-like QRS complexes
- - Less realistic but computationally efficient
+## ECG-derived respiration
-**Key parameters:**
-- `heart_rate`: Average BPM (default: 70)
-- `heart_rate_std`: Heart rate variability magnitude (default: 1)
-- `noise`: Gaussian noise level (default: 0.01)
-- `random_state`: Seed for reproducibility
-
-### ecg_plot()
-
-Visualize processed ECG with detected R-peaks and signal quality.
+`ecg_rsp()` takes a heart-rate series, not raw/clean ECG:
```python
-nk.ecg_plot(signals, info)
+edr = nk.ecg_rsp(signals["ECG_Rate"], sampling_rate=250, method="vangent2019")
```
-**Displays:**
-- Raw and cleaned ECG signals
-- Detected R-peaks overlaid
-- Heart rate trace
-- Signal quality indicators
-
-## ECG-Specific Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 250 Hz for basic R-peak detection
-- **Recommended**: 500-1000 Hz for waveform delineation
-- **High-resolution**: 2000+ Hz for detailed morphology analysis
-
-### Signal Duration Requirements
-- **R-peak detection**: Any duration (≥2 beats minimum)
-- **Basic heart rate**: ≥10 seconds
-- **HRV time domain**: ≥60 seconds
-- **HRV frequency domain**: 1-5 minutes (optimal)
-- **Ultra-low frequency HRV**: ≥24 hours
+EDR is a proxy and depends on ECG morphology/rate modulation. It is not interchangeable
+with a calibrated respiration sensor for RSA, tidal volume, or respiratory diagnosis.
-### Common Issues and Solutions
+## Bounded pipeline
-**Poor R-peak detection:**
-- Try different methods: `method='pantompkins1985'` often robust
-- Ensure adequate sampling rate (≥250 Hz)
-- Check for inverted ECG: use `ecg_invert()`
-- Apply artifact correction: `correct_artifacts=True`
-
-**Noisy signal:**
-- Use appropriate cleaning method for noise type
-- Adjust powerline frequency if outside US/Europe
-- Consider signal quality assessment before analysis
-
-**Missing waveform components:**
-- Increase sampling rate (≥500 Hz for delineation)
-- Try different delineation methods (`'dwt'`, `'peak'`, `'cwt'`)
-- Verify signal quality with `ecg_quality()`
-
-## Integration with Other Signals
-
-### ECG + RSP: Respiratory Sinus Arrhythmia
-```python
-# Process both signals
-ecg_signals, ecg_info = nk.ecg_process(ecg, sampling_rate=1000)
-rsp_signals, rsp_info = nk.rsp_process(rsp, sampling_rate=1000)
-
-# Compute RSA
-rsa = nk.hrv_rsa(ecg_info['ECG_R_Peaks'], rsp_signals['RSP_Clean'], sampling_rate=1000)
+```bash
+python skills/neurokit2/scripts/ecg_hrv_pipeline.py \
+ --input deidentified.csv --column ECG --root . --deidentified \
+ --sampling-rate 250 --method neurokit --domains time \
+ --signals-output ecg_processed.csv --output ecg_report.json
```
-### Multi-modal Integration
-```python
-# Process multiple signals at once
-bio_signals, bio_info = nk.bio_process(
- ecg=ecg_signal,
- rsp=rsp_signal,
- eda=eda_signal,
- sampling_rate=1000
-)
-```
+The helper rejects missing/non-finite samples instead of silently interpolating them,
+reports observed schemas and correction categories, and gates longer HRV domains.
-## References
+## Sources checked 2026-07-23
-- Pan, J., & Tompkins, W. J. (1985). A real-time QRS detection algorithm. IEEE transactions on biomedical engineering, 32(3), 230-236.
-- Hamilton, P. (2002). Open source ECG analysis. Computers in cardiology, 101-104.
-- Martinez, J. P., Almeida, R., Olmos, S., Rocha, A. P., & Laguna, P. (2004). A wavelet-based ECG delineator: evaluation on standard databases. IEEE Transactions on biomedical engineering, 51(4), 570-581.
-- Lipponen, J. A., & Tarvainen, M. P. (2019). A robust algorithm for heart rate variability time series artefact correction using novel beat classification. Journal of medical engineering & technology, 43(3), 173-181.
+- [Official ECG API](https://neuropsychology.github.io/NeuroKit/functions/ecg.html)
+- [Stable v0.2.13 `ecg_process` source](https://github.com/neuropsychology/NeuroKit/blob/v0.2.13/neurokit2/ecg/ecg_process.py)
+- [Quigley et al. (2024), HR/HRV measurement guidelines](https://doi.org/10.1111/psyp.14604)
+- [Laborde et al. (2017), HRV planning/reporting](https://doi.org/10.3389/fpsyg.2017.00213)
+- [Lipponen & Tarvainen (2019), correction algorithm](https://doi.org/10.1080/03091902.2019.1640306)
+- [Pan & Tompkins (1985)](https://doi.org/10.1109/TBME.1985.325532)
diff --git a/skills/neurokit2/references/eda.md b/skills/neurokit2/references/eda.md
index 28b36aef..50aa3727 100644
--- a/skills/neurokit2/references/eda.md
+++ b/skills/neurokit2/references/eda.md
@@ -1,497 +1,185 @@
-# Electrodermal Activity (EDA) Analysis
+# Electrodermal activity
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official EDA API/examples, and Society for Psychophysiological Research guidance.
-Electrodermal Activity (EDA), also known as Galvanic Skin Response (GSR) or Skin Conductance (SC), measures the electrical conductance of the skin, reflecting sympathetic nervous system arousal and sweat gland activity. EDA is widely used in psychophysiology, affective computing, and lie detection.
+## Measurement contract
-## Main Processing Pipeline
+Record:
-### eda_process()
+- conductance versus resistance, physical unit, range, and calibration;
+- constant-voltage/current system and electrode material/area;
+- palmar/plantar or other site, laterality, placement, and skin preparation;
+- sampling rate, hardware filters, temperature, humidity, acclimation, and movement;
+- missing/detached/saturated intervals; and
+- participant/task factors and response definition.
-Automated processing of raw EDA signals returning tonic/phasic decomposition and SCR features.
+Do not infer microsiemens from `EDA` or compare arbitrary sensor units with published
+µS thresholds. Sensor site, hardware, environment, and population require validation.
-```python
-signals, info = nk.eda_process(eda_signal, sampling_rate=100, method='neurokit')
-```
-
-**Pipeline steps:**
-1. Signal cleaning (low-pass filtering)
-2. Tonic-phasic decomposition
-3. Skin conductance response (SCR) detection
-4. SCR feature extraction (onset, peak, amplitude, rise/recovery times)
-
-**Returns:**
-- `signals`: DataFrame with:
- - `EDA_Clean`: Filtered signal
- - `EDA_Tonic`: Slow-varying baseline
- - `EDA_Phasic`: Fast-varying responses
- - `SCR_Onsets`, `SCR_Peaks`, `SCR_Height`: Response markers
- - `SCR_Amplitude`, `SCR_RiseTime`, `SCR_RecoveryTime`: Response features
-- `info`: Dictionary with processing parameters
-
-**Methods:**
-- `'neurokit'`: cvxEDA decomposition + neurokit peak detection
-- `'biosppy'`: Median smoothing + biosppy approach
-
-## Preprocessing Functions
-
-### eda_clean()
-
-Remove noise through low-pass filtering.
+## Default stable pipeline
```python
-cleaned_eda = nk.eda_clean(eda_signal, sampling_rate=100, method='neurokit')
+signals, info = nk.eda_process(
+ eda,
+ sampling_rate=100,
+ method="neurokit",
+)
```
-**Methods:**
-- `'neurokit'`: Low-pass Butterworth filter (3 Hz cutoff)
-- `'biosppy'`: Low-pass Butterworth filter (5 Hz cutoff)
-
-**Automatic skipping:**
-- If sampling rate < 7 Hz, cleaning is skipped (already low-pass)
-
-**Rationale:**
-- EDA frequency content typically 0-3 Hz
-- Remove high-frequency noise and motion artifacts
-- Preserve slow SCRs (typical rise time 1-3 seconds)
+In stable 0.2.13 the NeuroKit pipeline performs cleaning, **high-pass**
+tonic/phasic decomposition, and NeuroKit SCR detection. It does not use cvxEDA by
+default.
-### eda_phasic()
+The pinned default schema observed:
-Decompose EDA into tonic (slow baseline) and phasic (rapid responses) components.
-
-```python
-tonic, phasic = nk.eda_phasic(eda_cleaned, sampling_rate=100, method='cvxeda')
+```text
+EDA_Raw, EDA_Clean, EDA_Tonic, EDA_Phasic,
+SCR_Onsets, SCR_Peaks, SCR_Height, SCR_Amplitude,
+SCR_RiseTime, SCR_Recovery, SCR_RecoveryTime
```
-**Methods:**
+`info` was a flat dict containing SCR arrays plus `sampling_rate`. Treat this as a
+default 0.2.13 observation, not a universal schema.
-**1. cvxEDA (default, recommended):**
-```python
-tonic, phasic = nk.eda_phasic(eda_cleaned, sampling_rate=100, method='cvxeda')
-```
-- Convex optimization approach (Greco et al., 2016)
-- Sparse phasic driver model
-- Most physiologically accurate
-- Computationally intensive but superior decomposition
+There is no public `eda_quality()` in stable 0.2.13. Quality must combine acquisition
+metadata, missing/flat/clipped/motion checks, raw/clean overlays, decomposition
+plausibility, and response review.
-**2. Median smoothing:**
-```python
-tonic, phasic = nk.eda_phasic(eda_cleaned, sampling_rate=100, method='smoothmedian')
-```
-- Median filter with configurable window
-- Fast, simple
-- Less accurate than cvxEDA
+## Make decomposition explicit
-**3. High-pass filtering (Biopac's Acqknowledge):**
```python
-tonic, phasic = nk.eda_phasic(eda_cleaned, sampling_rate=100, method='highpass')
+clean = nk.eda_clean(eda, sampling_rate=100, method="neurokit")
+components = nk.eda_phasic(
+ clean,
+ sampling_rate=100,
+ method="highpass",
+)
```
-- High-pass filter (0.05 Hz) extracts phasic
-- Fast computation
-- Tonic derived by subtraction
-**4. SparsEDA:**
-```python
-tonic, phasic = nk.eda_phasic(eda_cleaned, sampling_rate=100, method='sparseda')
-```
-- Sparse deconvolution approach
-- Alternative optimization method
+`eda_clean()` options include `neurokit`, `biosppy`, and `none`. The NeuroKit path
+uses a 3 Hz low-pass, and skips it below 7 Hz.
-**Returns:**
-- `tonic`: Slow-varying skin conductance level (SCL)
-- `phasic`: Fast skin conductance responses (SCRs)
+`eda_phasic()` returns a DataFrame with `EDA_Tonic` and `EDA_Phasic`. Methods include:
-**Physiological interpretation:**
-- **Tonic (SCL)**: Baseline arousal, general activation, hydration
-- **Phasic (SCR)**: Event-related responses, orienting, emotional reactions
+- `highpass`: default stable method; phasic high-pass separation;
+- `smoothmedian`: median-smoothed tonic estimate;
+- `cvxeda`: convex optimization; needs optional `cvxopt`;
+- `sparseda`: sparse decomposition.
-### eda_peaks()
+These methods estimate different latent components and are not interchangeable.
+Report method, all kwargs, optional dependency versions, convergence/failure behavior,
+and sensitivity. Do not call one decomposition “physiologically true” without
+appropriate validation.
-Detect Skin Conductance Responses (SCRs) in phasic component.
+## SCR detection
```python
-peaks, info = nk.eda_peaks(eda_phasic, sampling_rate=100, method='neurokit',
- amplitude_min=0.1)
+markers, peak_info = nk.eda_peaks(
+ components["EDA_Phasic"],
+ sampling_rate=100,
+ method="neurokit",
+ amplitude_min=0.1,
+)
```
-**Methods:**
-- `'neurokit'`: Optimized for reliability, configurable thresholds
-- `'gamboa2008'`: Gamboa's algorithm
-- `'kim2004'`: Kim's approach
-- `'vanhalem2020'`: Van Halem's method
-- `'nabian2018'`: Nabian's algorithm
-
-**Key parameters:**
-- `amplitude_min`: Minimum SCR amplitude (default: 0.1 µS)
- - Too low: false positives from noise
- - Too high: miss small but valid responses
-- `rise_time_max`: Maximum rise time (default: 2 seconds)
-- `rise_time_min`: Minimum rise time (default: 0.01 seconds)
-
-**Returns:**
-- Dictionary with:
- - `SCR_Onsets`: Indices where SCR begins
- - `SCR_Peaks`: Indices of peak amplitude
- - `SCR_Height`: Peak height above baseline
- - `SCR_Amplitude`: Onset-to-peak amplitude
- - `SCR_RiseTime`: Onset-to-peak duration
- - `SCR_RecoveryTime`: Peak-to-recovery duration (50% decay)
-
-**SCR timing conventions:**
-- **Latency**: 1-3 seconds after stimulus (typical)
-- **Rise time**: 0.5-3 seconds
-- **Recovery time**: 2-10 seconds (to 50% recovery)
-- **Minimum amplitude**: 0.01-0.05 µS (detection threshold)
-
-### eda_fixpeaks()
-
-Correct detected SCR peaks (currently placeholder for EDA).
+Stable methods include `neurokit`, `gamboa2008`, `kim2004`, `vanhalem2020`, and
+`nabian2018`. For `neurokit` and `kim2004`, `amplitude_min` is a fraction relative to
+the largest amplitude in the analyzed signal—not an absolute µS threshold.
-```python
-corrected_peaks = nk.eda_fixpeaks(peaks)
-```
+`eda_peaks()` returns `(signals, info)`:
-**Note:** Less critical for EDA than cardiac signals due to slower dynamics.
+- marker/feature DataFrame: `SCR_Onsets`, `SCR_Peaks`, `SCR_Height`,
+ `SCR_Amplitude`, `SCR_RiseTime`, `SCR_Recovery`, `SCR_RecoveryTime`;
+- info dict: event-indexed arrays and sampling rate.
-## Analysis Functions
+Marker columns are same-length arrays; feature values are placed at relevant marker
+locations and are otherwise missing. Use `info` for event-level arrays. Do not average
+same-length feature columns as if every sample were an independent response.
-### eda_analyze()
+`eda_fixpeaks()` is documented as a placeholder that does not currently correct EDA
+peaks.
-Automatically select appropriate analysis type based on data duration.
+## Missingness and artifacts
-```python
-analysis = nk.eda_analyze(signals, sampling_rate=100)
-```
+EDA motion/electrode artifacts can resemble fast responses, while detachment can look
+flat. Before decomposition:
-**Mode selection:**
-- Duration < 10 seconds → `eda_eventrelated()`
-- Duration ≥ 10 seconds → `eda_intervalrelated()`
+1. inspect raw units, range, clipping, steps, flatlines, and missing runs;
+2. segment long discontinuities;
+3. annotate motion, temperature changes, and contact problems;
+4. avoid broad interpolation across SCR morphology; and
+5. keep an artifact/validity mask through epoching.
-**Returns:**
-- DataFrame with EDA metrics appropriate for analysis mode
+Filtering cannot restore a detached or saturated channel. A low response count can be
+physiological, methodological, or a sensor failure; it is not automatically a
+“non-responder.”
-### eda_eventrelated()
+## Event-related EDA
-Analyze stimulus-locked EDA epochs for event-related responses.
+Create epochs only after event and signal clocks are aligned:
```python
-results = nk.eda_eventrelated(epochs)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=100,
+ epochs_start=-1,
+ epochs_end=10,
+ baseline_correction=False,
+)
+features = nk.eda_eventrelated(epochs)
```
-**Computed metrics (per epoch):**
-- `EDA_SCR`: Presence of SCR (binary: 0 or 1)
-- `SCR_Amplitude`: Maximum SCR amplitude during epoch
-- `SCR_Magnitude`: Mean phasic activity
-- `SCR_Peak_Amplitude`: Onset-to-peak amplitude
-- `SCR_RiseTime`: Time to peak from onset
-- `SCR_RecoveryTime`: Time to 50% recovery
-- `SCR_Latency`: Delay from stimulus to SCR onset
-- `EDA_Tonic`: Mean tonic level during epoch
-
-**Typical parameters:**
-- Epoch duration: 0-10 seconds post-stimulus
-- Baseline: -1 to 0 seconds pre-stimulus
-- Expected SCR latency: 1-3 seconds
-
-**Use cases:**
-- Emotional stimulus processing (images, sounds)
-- Cognitive load assessment (mental arithmetic)
-- Anticipation and prediction error
-- Orienting responses
+Stable event-related output is conditional on available columns. Documented features
+include `EDA_SCR`, first-response amplitude/time/rise/recovery fields, tonic/phasic
+summaries, labels, conditions, and event onset. Inspect `features.columns`.
-### eda_intervalrelated()
+Prespecify response latency/window, overlap handling, baseline approach, minimum
+amplitude definition, non-response coding, and trial artifact rules. Slow responses can
+overlap adjacent events; a peak in a window is not automatically elicited by that event.
-Analyze extended EDA recordings for overall arousal and activation patterns.
+## Interval analysis and sympathetic index
```python
-results = nk.eda_intervalrelated(signals, sampling_rate=100)
+features = nk.eda_intervalrelated(signals, sampling_rate=100)
```
-**Computed metrics:**
-- `SCR_Peaks_N`: Number of SCRs detected
-- `SCR_Peaks_Amplitude_Mean`: Average SCR amplitude
-- `EDA_Tonic_Mean`, `EDA_Tonic_SD`: Tonic level statistics
-- `EDA_Sympathetic`: Sympathetic nervous system index
-- `EDA_SympatheticN`: Normalized sympathetic index
-- `EDA_Autocorrelation`: Temporal structure (lag 4 seconds)
-- `EDA_Phasic_*`: Mean, SD, min, max of phasic component
+The pinned official example showed six columns, including SCR count/amplitude,
+`EDA_Tonic_SD`, `EDA_Sympathetic`, `EDA_SympatheticN`, and
+`EDA_Autocorrelation`; output depends on duration and available columns.
-**Recording duration:**
-- **Minimum**: 10 seconds
-- **Recommended**: 60+ seconds for stable SCR rate
-- **Sympathetic index**: ≥64 seconds required
+`eda_sympathetic()` supports `posada` and `ghiasi`, with a default 0.045–0.25 Hz
+band. The implementation/documentation uses at least 64 seconds to support the spectral
+estimate. Report exact usable duration, frequency band, estimator, normalization, and
+units. Do not turn this index into a direct clinical sympathetic-state measure.
-**Use cases:**
-- Resting state arousal assessment
-- Stress level monitoring
-- Baseline sympathetic activity
-- Long-term affective state
+## Bounded pipeline
-## Specialized Analysis Functions
-
-### eda_sympathetic()
-
-Derive sympathetic nervous system activity from frequency band (0.045-0.25 Hz).
-
-```python
-sympathetic = nk.eda_sympathetic(signals, sampling_rate=100, method='posada',
- show=False)
+```bash
+python skills/neurokit2/scripts/eda_pipeline.py \
+ --input deidentified.csv --column EDA --root . --deidentified \
+ --sampling-rate 100 --unit uS \
+ --clean-method neurokit --phasic-method highpass \
+ --peak-method neurokit --amplitude-min 0.1
```
-**Methods:**
-- `'posada'`: Posada-Quintero method (2016)
- - Spectral power in 0.045-0.25 Hz band
- - Validated against other autonomic measures
-- `'ghiasi'`: Ghiasi method (2018)
- - Alternative frequency-based approach
-
-**Requirements:**
-- **Minimum duration**: 64 seconds
-- Sufficient for frequency resolution in target band
-
-**Returns:**
-- `EDA_Sympathetic`: Sympathetic index (absolute)
-- `EDA_SympatheticN`: Normalized sympathetic index (0-1)
-
-**Interpretation:**
-- Higher values: increased sympathetic arousal
-- Reflects tonic sympathetic activity, not phasic responses
-- Complements SCR analysis
-
-**Use cases:**
-- Stress assessment
-- Arousal monitoring over time
-- Cognitive load measurement
-- Complementary to HRV for autonomic balance
-
-### eda_autocor()
-
-Compute autocorrelation to assess temporal structure of EDA signal.
-
-```python
-autocorr = nk.eda_autocor(eda_phasic, sampling_rate=100, lag=4)
-```
+The helper rejects missing/non-finite samples, records the observed schema, and makes
+decomposition/threshold semantics explicit.
-**Parameters:**
-- `lag`: Time lag in seconds (default: 4 seconds)
+## Interpretation boundary
-**Interpretation:**
-- High autocorrelation: persistent, slowly-varying signal
-- Low autocorrelation: rapid, uncorrelated fluctuations
-- Reflects temporal regularity of SCRs
+EDA indexes eccrine sweat-gland activity under the recording conditions. It does not
+uniquely identify stress, emotion, deception, pain, diagnosis, or intent. Compare
+within a theory-driven design with contextual measures and validated preprocessing.
+Do not use this workflow for clinical/driver/workplace monitoring or medical-device
+validation.
-**Use case:**
-- Assess signal quality
-- Characterize response patterns
-- Distinguish sustained vs. transient arousal
-
-### eda_changepoints()
-
-Detect abrupt shifts in mean and variance of EDA signal.
-
-```python
-changepoints = nk.eda_changepoints(eda_phasic, penalty=10000, show=False)
-```
-
-**Method:**
-- Penalty-based segmentation
-- Identifies transitions between states
-
-**Parameters:**
-- `penalty`: Controls sensitivity (default: 10,000)
- - Higher penalty: fewer, more robust changepoints
- - Lower penalty: more sensitive to small changes
-
-**Returns:**
-- Indices of detected changepoints
-- Optional visualization of segments
-
-**Use cases:**
-- Identify state transitions in continuous monitoring
-- Segment data by arousal level
-- Detect phase changes in experiments
-- Automated epoch definition
-
-## Visualization
-
-### eda_plot()
-
-Create static or interactive visualizations of processed EDA.
-
-```python
-nk.eda_plot(signals, info, static=True)
-```
-
-**Displays:**
-- Raw and cleaned EDA signal
-- Tonic and phasic components
-- Detected SCR onsets, peaks, and recovery
-- Sympathetic index time course (if computed)
-
-**Interactive mode (`static=False`):**
-- Plotly-based interactive exploration
-- Zoom, pan, hover for details
-- Export to image formats
-
-## Simulation and Testing
-
-### eda_simulate()
-
-Generate synthetic EDA signals with configurable parameters.
-
-```python
-synthetic_eda = nk.eda_simulate(duration=10, sampling_rate=100, scr_number=3,
- noise=0.01, drift=0.01)
-```
-
-**Parameters:**
-- `duration`: Signal length in seconds
-- `sampling_rate`: Sampling frequency (Hz)
-- `scr_number`: Number of SCRs to include
-- `noise`: Gaussian noise level
-- `drift`: Slow baseline drift magnitude
-- `random_state`: Seed for reproducibility
-
-**Returns:**
-- Synthetic EDA signal with realistic SCR morphology
-
-**Use cases:**
-- Algorithm testing and validation
-- Educational demonstrations
-- Method comparison
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 10 Hz (adequate for slow SCRs)
-- **Standard**: 20-100 Hz (most commercial systems)
-- **High-resolution**: 1000 Hz (research-grade, oversampled)
-
-### Recording Duration
-- **SCR detection**: ≥10 seconds (depends on stimulus)
-- **Event-related**: Typically 10-20 seconds per trial
-- **Interval-related**: ≥60 seconds for stable estimates
-- **Sympathetic index**: ≥64 seconds (frequency resolution)
-
-### Electrode Placement
-- **Standard sites**:
- - Palmar: distal/middle phalanges (fingers)
- - Plantar: sole of foot
-- **High density**: Thenar/hypothenar eminence
-- **Avoid**: Hairy skin, low sweat gland density areas
-- **Bilateral**: Left vs. right hand (typically similar)
-
-### Signal Quality Issues
-
-**Flat signal (no variation):**
-- Check electrode contact and gel
-- Verify proper placement on sweat gland-rich areas
-- Allow 5-10 minute adaptation period
-
-**Excessive noise:**
-- Movement artifacts: minimize participant motion
-- Electrical interference: check grounding, shielding
-- Thermal effects: control room temperature
-
-**Baseline drift:**
-- Normal: slow changes over minutes
-- Excessive: electrode polarization, poor contact
-- Solution: use `eda_phasic()` to separate tonic drift
-
-**Non-responders:**
-- ~5-10% of population have minimal EDA
-- Genetic/physiological variation
-- Not indicative of equipment failure
-
-### Best Practices
-
-**Preprocessing workflow:**
-```python
-# 1. Clean signal
-cleaned = nk.eda_clean(eda_raw, sampling_rate=100, method='neurokit')
-
-# 2. Decompose tonic/phasic
-tonic, phasic = nk.eda_phasic(cleaned, sampling_rate=100, method='cvxeda')
-
-# 3. Detect SCRs
-signals, info = nk.eda_peaks(phasic, sampling_rate=100, amplitude_min=0.05)
-
-# 4. Analyze
-analysis = nk.eda_analyze(signals, sampling_rate=100)
-```
-
-**Event-related workflow:**
-```python
-# 1. Process signal
-signals, info = nk.eda_process(eda_raw, sampling_rate=100)
-
-# 2. Find events
-events = nk.events_find(trigger_channel, threshold=0.5)
-
-# 3. Create epochs (-1 to 10 seconds around stimulus)
-epochs = nk.epochs_create(signals, events, sampling_rate=100,
- epochs_start=-1, epochs_end=10)
-
-# 4. Event-related analysis
-results = nk.eda_eventrelated(epochs)
-
-# 5. Statistical analysis
-# Compare SCR amplitude across conditions
-```
+## Sources checked 2026-07-23
-## Clinical and Research Applications
-
-**Emotion and affective science:**
-- Arousal dimension of emotion (not valence)
-- Emotional picture viewing
-- Music-induced emotion
-- Fear conditioning
-
-**Cognitive processes:**
-- Mental workload and effort
-- Attention and vigilance
-- Decision-making and uncertainty
-- Error processing
-
-**Clinical populations:**
-- Anxiety disorders: heightened baseline, exaggerated responses
-- PTSD: fear conditioning, extinction deficits
-- Autism: atypical arousal patterns
-- Psychopathy: reduced fear responses
-
-**Applied settings:**
-- Lie detection (polygraph)
-- User experience research
-- Driver monitoring
-- Stress assessment in real-world settings
-
-**Neuroimaging integration:**
-- fMRI: EDA correlates with amygdala, insula activity
-- Concurrent recording during brain imaging
-- Autonomic-brain coupling
-
-## Interpretation Guidelines
-
-**SCR amplitude:**
-- **0.01-0.05 µS**: Small but detectable
-- **0.05-0.2 µS**: Moderate response
-- **>0.2 µS**: Large response
-- **Context-dependent**: Normalize within-subject
-
-**SCR frequency:**
-- **Resting**: 1-3 SCRs per minute (typical)
-- **Stressed**: >5 SCRs per minute
-- **Non-specific SCRs**: Spontaneous (no identifiable stimulus)
-
-**Tonic SCL:**
-- **Range**: 2-20 µS (highly variable across individuals)
-- **Within-subject changes** more interpretable than absolute levels
-- **Increases**: arousal, stress, cognitive load
-- **Decreases**: relaxation, habituation
-
-## References
-
-- Boucsein, W. (2012). Electrodermal activity (2nd ed.). Springer Science & Business Media.
-- Greco, A., Valenza, G., & Scilingo, E. P. (2016). cvxEDA: A convex optimization approach to electrodermal activity processing. IEEE Transactions on Biomedical Engineering, 63(4), 797-804.
-- Posada-Quintero, H. F., Florian, J. P., Orjuela-Cañón, A. D., Aljama-Corrales, T., Charleston-Villalobos, S., & Chon, K. H. (2016). Power spectral density analysis of electrodermal activity for sympathetic function assessment. Annals of biomedical engineering, 44(10), 3124-3135.
-- Dawson, M. E., Schell, A. M., & Filion, D. L. (2017). The electrodermal system. In Handbook of psychophysiology (pp. 217-243). Cambridge University Press.
+- [Official EDA API](https://neuropsychology.github.io/NeuroKit/functions/eda.html)
+- [Official SCR example](https://neuropsychology.github.io/NeuroKit/examples/eda_peaks/eda_peaks.html)
+- [Stable v0.2.13 EDA source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/eda)
+- [SPR Ad Hoc Committee (2012), publication recommendations](https://doi.org/10.1111/j.1469-8986.2012.01384.x)
+- [Greco et al. (2016), cvxEDA](https://doi.org/10.1109/TBME.2015.2474131)
+- [NeuroKit2 main paper](https://doi.org/10.3758/s13428-020-01516-y)
diff --git a/skills/neurokit2/references/eeg.md b/skills/neurokit2/references/eeg.md
index 31bee110..7260c403 100644
--- a/skills/neurokit2/references/eeg.md
+++ b/skills/neurokit2/references/eeg.md
@@ -1,506 +1,204 @@
-# EEG Analysis and Microstates
+# EEG and microstates
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable source/runtime,
+the official EEG/microstate APIs, and SPR EEG/MEG guidance.
-Analyze electroencephalography (EEG) signals for frequency band power, channel quality assessment, source localization, and microstate identification. NeuroKit2 integrates with MNE-Python for comprehensive EEG processing workflows.
+## Scope
-## Core EEG Functions
+NeuroKit2 does not expose an `eeg_process()` equivalent to its ECG/EDA pipelines.
+It provides selected feature, QC, re-reference, MNE, source, and microstate helpers.
+Use MNE or another validated EEG framework for the full acquisition/preprocessing
+workflow, while recording every transform and bad-segment decision.
-### eeg_power()
+For NumPy input, NeuroKit2 EEG functions expect shape:
-Compute power across standard frequency bands for specified channels.
-
-```python
-power = nk.eeg_power(eeg_data, sampling_rate=250, channels=['Fz', 'Cz', 'Pz'],
- frequency_bands={'Delta': (0.5, 4),
- 'Theta': (4, 8),
- 'Alpha': (8, 13),
- 'Beta': (13, 30),
- 'Gamma': (30, 45)})
-```
-
-**Standard frequency bands:**
-- **Delta (0.5-4 Hz)**: Deep sleep, unconscious processes
-- **Theta (4-8 Hz)**: Drowsiness, meditation, memory encoding
-- **Alpha (8-13 Hz)**: Relaxed wakefulness, eyes closed
-- **Beta (13-30 Hz)**: Active thinking, focus, anxiety
-- **Gamma (30-45 Hz)**: Cognitive processing, binding
-
-**Returns:**
-- DataFrame with power values for each channel × frequency band combination
-- Columns: `Channel_Band` (e.g., 'Fz_Alpha', 'Cz_Beta')
-
-**Use cases:**
-- Resting state analysis
-- Cognitive state classification
-- Sleep staging
-- Meditation or neurofeedback monitoring
-
-### eeg_badchannels()
-
-Identify problematic channels using statistical outlier detection.
-
-```python
-bad_channels = nk.eeg_badchannels(eeg_data, sampling_rate=250, bad_threshold=2)
-```
-
-**Detection methods:**
-- Standard deviation outliers across channels
-- Correlation with other channels
-- Flat or dead channels
-- Channels with excessive noise
-
-**Parameters:**
-- `bad_threshold`: Z-score threshold for outlier detection (default: 2)
-
-**Returns:**
-- List of channel names identified as problematic
-
-**Use case:**
-- Quality control before analysis
-- Automatic bad channel rejection
-- Interpolation or exclusion decisions
-
-### eeg_rereference()
-
-Re-express voltage measurements relative to different reference points.
-
-```python
-rereferenced = nk.eeg_rereference(eeg_data, reference='average', robust=False)
-```
-
-**Reference types:**
-- `'average'`: Average reference (mean of all electrodes)
-- `'REST'`: Reference Electrode Standardization Technique
-- `'bipolar'`: Differential recording between electrode pairs
-- Specific channel name: Use single electrode as reference
-
-**Common references:**
-- **Average reference**: Most common for high-density EEG
-- **Linked mastoids**: Traditional clinical EEG
-- **Vertex (Cz)**: Sometimes used in ERP research
-- **REST**: Approximates infinity reference
-
-**Returns:**
-- Re-referenced EEG data
-
-### eeg_gfp()
-
-Compute Global Field Power - the standard deviation of all electrodes at each time point.
-
-```python
-gfp = nk.eeg_gfp(eeg_data)
-```
-
-**Interpretation:**
-- High GFP: Strong, synchronized brain activity across regions
-- Low GFP: Weak or desynchronized activity
-- GFP peaks: Points of stable topography, used for microstate detection
-
-**Use cases:**
-- Identify periods of stable topographic patterns
-- Select time points for microstate analysis
-- Event-related potential (ERP) visualization
-
-### eeg_diss()
-
-Measure topographic dissimilarity between electric field configurations.
-
-```python
-dissimilarity = nk.eeg_diss(eeg_data1, eeg_data2, method='gfp')
-```
-
-**Methods:**
-- GFP-based: Normalized difference
-- Spatial correlation
-- Cosine distance
-
-**Use case:**
-- Compare topographies between conditions
-- Microstate transition analysis
-- Template matching
-
-## Source Localization
-
-### eeg_source()
-
-Perform source reconstruction to estimate brain-level activity from scalp recordings.
-
-```python
-sources = nk.eeg_source(eeg_data, method='sLORETA')
-```
-
-**Methods:**
-- `'sLORETA'`: Standardized Low-Resolution Electromagnetic Tomography
- - Zero localization error for point sources
- - Good spatial resolution
-- `'MNE'`: Minimum Norm Estimate
- - Fast, well-established
- - Bias toward superficial sources
-- `'dSPM'`: Dynamic Statistical Parametric Mapping
- - Normalized MNE
-- `'eLORETA'`: Exact LORETA
- - Improved localization accuracy
-
-**Requirements:**
-- Forward model (lead field matrix)
-- Co-registered electrode positions
-- Head model (boundary element or spherical)
-
-**Returns:**
-- Source space activity estimates
-
-### eeg_source_extract()
-
-Extract activity from specific anatomical brain regions.
-
-```python
-regional_activity = nk.eeg_source_extract(sources, regions=['PFC', 'MTL', 'Parietal'])
-```
-
-**Region options:**
-- Standard atlases: Desikan-Killiany, Destrieux, AAL
-- Custom ROIs
-- Brodmann areas
-
-**Returns:**
-- Time series for each region
-- Averaged or principal component across voxels
-
-**Use cases:**
-- Region-of-interest analysis
-- Functional connectivity
-- Source-level statistics
-
-## Microstate Analysis
-
-Microstates are brief (80-120 ms) periods of stable brain topography, representing coordinated neural networks. Typically 4-7 microstate classes (often labeled A, B, C, D) with distinct functions.
-
-### microstates_segment()
-
-Identify and extract microstates using clustering algorithms.
-
-```python
-microstates = nk.microstates_segment(eeg_data, n_microstates=4, sampling_rate=250,
- method='kmod', normalize=True)
+```text
+(channels, time_samples)
```
-**Methods:**
-- `'kmod'` (default): Modified k-means optimized for EEG topographies
- - Polarity-invariant clustering
- - Most common in microstate literature
-- `'kmeans'`: Standard k-means clustering
-- `'kmedoids'`: K-medoids (more robust to outliers)
-- `'pca'`: Principal component analysis
-- `'ica'`: Independent component analysis
-- `'aahc'`: Atomize and agglomerate hierarchical clustering
-
-**Parameters:**
-- `n_microstates`: Number of microstate classes (typically 4-7)
-- `normalize`: Normalize topographies (recommended: True)
-- `n_inits`: Number of random initializations (increase for stability)
+Do not pass `(time, channels)` silently. Preserve channel names/order, montage,
+reference, sensor locations, units (typically volts in MNE), sampling rate, and bad
+channel/segment annotations.
-**Returns:**
-- Dictionary with:
- - `'maps'`: Microstate template topographies
- - `'labels'`: Microstate label at each time point
- - `'gfp'`: Global field power
- - `'gev'`: Global explained variance
+## Current stable helpers
-### microstates_findnumber()
-
-Estimate the optimal number of microstates.
+### Power
```python
-optimal_k = nk.microstates_findnumber(eeg_data, show=True)
+power = nk.eeg_power(
+ eeg_channels_by_time,
+ sampling_rate=250,
+ frequency_band=["Gamma", "Beta", "Alpha", "Theta", "Delta"],
+)
```
-**Criteria:**
-- **Global Explained Variance (GEV)**: Percentage of variance explained
- - Elbow method: find "knee" in GEV curve
- - Typically 70-80% GEV achieved
-- **Krzanowski-Lai (KL) Criterion**: Statistical measure balancing fit and parsimony
- - Maximum KL indicates optimal k
-
-**Typical range:** 4-7 microstates
-- 4 microstates: Classic A, B, C, D states
-- 5-7 microstates: Finer-grained decomposition
-
-### microstates_classify()
-
-Reorder microstates based on anterior-posterior and left-right channel values.
+The argument is singular `frequency_band`, not `frequency_bands`. The pinned default
+array probe returned one row per channel with:
-```python
-classified = nk.microstates_classify(microstates)
+```text
+Channel, Gamma, Beta, Alpha, Theta, Delta
```
-**Purpose:**
-- Standardize microstate labels across subjects
-- Match conventional A, B, C, D topographies:
- - **A**: Left-right orientation, parieto-occipital
- - **B**: Right-left orientation, fronto-temporal
- - **C**: Anterior-posterior orientation, frontal-central
- - **D**: Fronto-central, anterior-posterior (inverse of C)
-
-**Returns:**
-- Reordered microstate maps and labels
+Standard named bands in the docs include Delta 1–4, Theta 4–8, Alpha 8–13, Beta
+13–30, and Gamma 30–80 Hz, with additional sub-bands. Band definitions are conventions,
+not universal physiology. Report exact boundaries, PSD parameters, reference, artifact
+handling, absolute/relative normalization, and usable duration.
-### microstates_clean()
-
-Preprocess EEG data for microstate extraction.
+### Bad channels
```python
-cleaned_eeg = nk.microstates_clean(eeg_data, sampling_rate=250)
+bads, channel_info = nk.eeg_badchannels(
+ eeg_channels_by_time,
+ bad_threshold=0.5,
+ distance_threshold=0.99,
+ show=False,
+)
```
-**Preprocessing steps:**
-- Bandpass filtering (typically 2-20 Hz)
-- Artifact rejection
-- Bad channel interpolation
-- Re-referencing to average
-
-**Rationale:**
-- Microstates reflect large-scale network activity
-- High-frequency and low-frequency artifacts can distort topographies
+Return order is a list plus a DataFrame. The pinned info schema contained `SD`, `Mean`,
+`MAD`, `Median`, `Skewness`, `Kurtosis`, `Amplitude`, interval bounds,
+`n_ZeroCrossings`, and `Bad`.
-### microstates_peaks()
+This statistical screen is not a universal rejection rule. Review raw data, montage,
+bridging, line noise, drift, channel location, task, and condition. Fit thresholds
+without leaking group/condition outcomes.
-Identify GFP peaks for microstate analysis.
+### Re-reference, GFP, and dissimilarity
```python
-peak_indices = nk.microstates_peaks(eeg_data, sampling_rate=250)
+rereferenced = nk.eeg_rereference(eeg_channels_by_time, reference="average")
+gfp = nk.eeg_gfp(rereferenced, method="l1")
+diss = nk.eeg_diss(rereferenced, gfp=gfp)
```
-**Purpose:**
-- Microstates typically analyzed at GFP peaks
-- Peaks represent moments of maximal, stable topographic activity
-- Reduces computational load and noise sensitivity
+For array input `eeg_rereference()` returns an array. For MNE input it returns an MNE
+object. Average reference requires adequate channel coverage and bad-channel handling;
+it is not automatically appropriate for sparse montages.
-**Returns:**
-- Indices of GFP local maxima
+`eeg_gfp()` defaults to L1 in NeuroKit2, while publications may use other definitions.
+Report method, standardization, normalization, smoothing, and reference.
-### microstates_static()
+## Optional MNE requirements
-Compute temporal properties of individual microstates.
-
-```python
-static_metrics = nk.microstates_static(microstates)
-```
+Core NeuroKit2 does not install MNE. Stable functions that require it include:
-**Metrics:**
-- **Duration (ms)**: Mean time spent in each microstate
- - Typical: 80-120 ms
- - Reflects stability and persistence
-- **Occurrence (per second)**: Frequency of microstate appearances
- - How often each state is entered
-- **Coverage (%)**: Percentage of total time in each microstate
- - Relative dominance
-- **Global Explained Variance (GEV)**: Variance explained by each class
- - Quality of template fit
+- `eeg_simulate()` (confirmed by pinned runtime);
+- `mne_data()` and MNE object helpers;
+- `eeg_source()` / `eeg_source_extract()`; and
+- `mne_templateMRI()`.
-**Returns:**
-- DataFrame with metrics for each microstate class
+Add only the optional package(s) required for the analysis at reviewed exact versions,
+commit/review the resulting `uv.lock`, and install with `uv sync --locked`. Do not
+install the upstream floating `full` extra in an automated workflow without such a
+lock.
-**Interpretation:**
-- Changes in duration: altered network stability
-- Changes in occurrence: shifting state dynamics
-- Changes in coverage: dominance of specific networks
+Some MNE helpers download datasets/templates. Treat network access, cache paths,
+licenses, versions, and checksums as study dependencies; do not use them in a
+restricted/offline workflow without prior provisioning.
-### microstates_dynamic()
+## Source reconstruction
-Analyze transition patterns between microstates.
+Stable signature:
-```python
-dynamic_metrics = nk.microstates_dynamic(microstates)
-```
-
-**Metrics:**
-- **Transition matrix**: Probability of transitioning from state i to state j
- - Reveals preferential sequences
-- **Transition rate**: Overall transition frequency
- - Higher rate: more rapid switching
-- **Entropy**: Randomness of transitions
- - High entropy: unpredictable switching
- - Low entropy: stereotyped sequences
-- **Markov test**: Are transitions history-dependent?
-
-**Returns:**
-- Dictionary with transition statistics
-
-**Use cases:**
-- Identify abnormal microstate sequences in clinical populations
-- Network dynamics and flexibility
-- State-dependent information processing
-
-### microstates_plot()
-
-Visualize microstate topographies and time course.
-
-```python
-nk.microstates_plot(microstates, eeg_data)
+```text
+eeg_source(raw, src, bem, method="sLORETA", show=False, ...)
```
-**Displays:**
-- Topographic maps for each microstate class
-- GFP trace with microstate labels
-- Transition plot showing state sequences
-- Statistical summary
+It requires an MNE Raw object, source space, BEM/head model, montage/electrode
+locations, and appropriate co-registration. `eeg_source_extract(stc, src, ...)` returns
+region time series from a segmentation.
-## MNE Integration Utilities
+A template MRI does not validate localization for an individual or population.
+Report coordinate frames, digitization, head/conductivity model, inverse method,
+regularization, noise covariance, depth/orientation choices, atlas, and uncertainty.
+Do not use NeuroKit2 source estimates for diagnosis, surgical planning, or clinical
+localization.
-### mne_data()
+## Microstates
-Access sample datasets from MNE-Python.
+### Segmentation
```python
-raw = nk.mne_data(dataset='sample', directory=None)
+out = nk.microstates_segment(
+ eeg_channels_by_time,
+ n_microstates=4,
+ train="gfp",
+ method="kmod",
+ sampling_rate=250,
+ n_runs=50,
+ random_state=42,
+)
```
-**Available datasets:**
-- `'sample'`: Multi-modal (MEG/EEG) example
-- `'ssvep'`: Steady-state visual evoked potentials
-- `'eegbci'`: Motor imagery BCI dataset
-
-### mne_to_df() / mne_to_dict()
-
-Convert MNE objects to NeuroKit-compatible formats.
+Stable methods include `kmod`, `kmeans`, `kmedoids`, `pca`, `ica`, and `aahc`.
+The pinned 0.2.13 output dict included:
-```python
-df = nk.mne_to_df(raw)
-data_dict = nk.mne_to_dict(epochs)
+```text
+Microstates, Sequence, GEV, GEV_per_microstate, GFP,
+Polarity, Info, Info_algorithm
```
-**Use case:**
-- Work with MNE-processed data in NeuroKit2
-- Convert between formats for analysis
-
-### mne_channel_add() / mne_channel_extract()
+It did **not** use lowercase `maps`, `labels`, `gfp`, or `gev`. `Microstates` contains
+maps, and `Sequence` is the sample-wise class assignment.
-Manage individual channels in MNE objects.
+### Preparation and summaries
```python
-# Extract specific channels
-subset = nk.mne_channel_extract(raw, ['Fz', 'Cz', 'Pz'])
+clean, train_indices, gfp, input_info = nk.microstates_clean(
+ eeg_channels_by_time,
+ sampling_rate=250,
+ train="gfp",
+)
-# Add derived channels
-raw_with_eog = nk.mne_channel_add(raw, new_channel_data, ch_name='EOG')
+static = nk.microstates_static(out["Sequence"], sampling_rate=250)
+dynamic = nk.microstates_dynamic(out["Sequence"])
```
-### mne_crop()
+`microstates_clean()` is a utility for array normalization/standardization and training
+sample selection; it does not implement a full EEG artifact pipeline.
-Trim recordings by time or samples.
+`microstates_classify()` is experimental and requires two arguments:
```python
-cropped = nk.mne_crop(raw, tmin=10, tmax=100)
+sequence, maps = nk.microstates_classify(
+ out["Sequence"],
+ out["Microstates"],
+)
```
-### mne_templateMRI()
-
-Provide template anatomy for source localization.
-
-```python
-subjects_dir = nk.mne_templateMRI()
-```
-
-**Use case:**
-- Source analysis without individual MRI
-- Group-level source localization
-- fsaverage template brain
-
-### eeg_simulate()
-
-Generate synthetic EEG signals for testing.
-
-```python
-synthetic_eeg = nk.eeg_simulate(duration=60, sampling_rate=250, n_channels=32)
-```
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 100 Hz for basic power analysis
-- **Standard**: 250-500 Hz for most applications
-- **High-resolution**: 1000+ Hz for detailed temporal dynamics
-
-### Recording Duration
-- **Power analysis**: ≥2 minutes for stable estimates
-- **Microstates**: ≥2-5 minutes, longer preferred
-- **Resting state**: 3-10 minutes typical
-- **Event-related**: Depends on trial count (≥30 trials per condition)
-
-### Artifact Management
-- **Eye blinks**: Remove with ICA or regression
-- **Muscle artifacts**: High-pass filter (≥1 Hz) or manual rejection
-- **Bad channels**: Detect and interpolate before analysis
-- **Line noise**: Notch filter at 50/60 Hz
-
-### Best Practices
-
-**Power analysis:**
-```python
-# 1. Clean data
-cleaned = nk.signal_filter(eeg_data, sampling_rate=250, lowcut=0.5, highcut=45)
-
-# 2. Identify and interpolate bad channels
-bad = nk.eeg_badchannels(cleaned, sampling_rate=250)
-# Interpolate bad channels using MNE
-
-# 3. Re-reference
-rereferenced = nk.eeg_rereference(cleaned, reference='average')
-
-# 4. Compute power
-power = nk.eeg_power(rereferenced, sampling_rate=250, channels=channel_list)
-```
-
-**Microstate workflow:**
-```python
-# 1. Preprocess
-cleaned = nk.microstates_clean(eeg_data, sampling_rate=250)
-
-# 2. Determine optimal number of states
-optimal_k = nk.microstates_findnumber(cleaned, show=True)
-
-# 3. Segment microstates
-microstates = nk.microstates_segment(cleaned, n_microstates=optimal_k,
- sampling_rate=250, method='kmod')
-
-# 4. Classify to standard labels
-microstates = nk.microstates_classify(microstates)
-
-# 5. Compute temporal metrics
-static = nk.microstates_static(microstates)
-dynamic = nk.microstates_dynamic(microstates)
-
-# 6. Visualize
-nk.microstates_plot(microstates, cleaned)
-```
+Its classification depends on channel ordering, so it is not a reliable substitute for
+template matching with a defined montage.
-## Clinical and Research Applications
+`microstates_findnumber()` returns `(optimal_number, scores_dataframe)`. Choosing a
+state count from the same dataset and then testing selected-state effects can inflate
+research flexibility. Prespecify or cross-validate clustering choices and assess
+initialization stability.
-**Cognitive neuroscience:**
-- Attention, working memory, executive function
-- Language processing
-- Sensory perception
+## Preprocessing/reporting
-**Clinical populations:**
-- Epilepsy: seizure detection, localization
-- Alzheimer's disease: slowing of EEG, microstate alterations
-- Schizophrenia: altered microstates, especially state C
-- ADHD: increased theta/beta ratio
-- Depression: frontal alpha asymmetry
+At minimum report:
-**Consciousness research:**
-- Anesthesia monitoring
-- Disorders of consciousness
-- Sleep staging
+- hardware, montage/locations/reference/ground, unit, sample rate, online filters;
+- resampling, offline filters/notches, edge handling, and line frequency;
+- bad channels/segments and interpolation;
+- ocular/muscle/cardiac correction and ICA details;
+- epoch/baseline definitions and retained trials;
+- PSD/time-frequency estimator and normalization;
+- microstate input band/reference, GFP definition, training points, algorithm,
+ state count, runs/seed, polarity, smoothing, and fit/stability; and
+- exact NeuroKit2/MNE versions and observed schemas.
-**Neurofeedback:**
-- Real-time frequency band training
-- Alpha enhancement for relaxation
-- Beta enhancement for focus
+Avoid frequency-band mental-state labels such as “beta = anxiety” or
+“theta/beta = ADHD.” EEG features are not diagnosis, consciousness monitoring,
+anesthesia control, seizure detection, or neurofeedback validation without a separate
+validated system and intended-use evidence.
-## References
+## Sources checked 2026-07-23
-- Michel, C. M., & Koenig, T. (2018). EEG microstates as a tool for studying the temporal dynamics of whole-brain neuronal networks: A review. Neuroimage, 180, 577-593.
-- Pascual-Marqui, R. D., Michel, C. M., & Lehmann, D. (1995). Segmentation of brain electrical activity into microstates: model estimation and validation. IEEE Transactions on Biomedical Engineering, 42(7), 658-665.
-- Gramfort, A., Luessi, M., Larson, E., Engemann, D. A., Strohmeier, D., Brodbeck, C., ... & Hämäläinen, M. (2013). MEG and EEG data analysis with MNE-Python. Frontiers in neuroscience, 7, 267.
+- [Official EEG API](https://neuropsychology.github.io/NeuroKit/functions/eeg.html)
+- [Official microstates API](https://neuropsychology.github.io/NeuroKit/functions/microstates.html)
+- [Stable v0.2.13 EEG source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/eeg)
+- [Stable v0.2.13 microstates source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/microstates)
+- [Keil et al. (2014), EEG/MEG publication guidelines](https://doi.org/10.1111/psyp.12147)
+- [Keil et al. (2022), frequency/time-frequency guidelines](https://doi.org/10.1111/psyp.14052)
+- [Michel & Koenig (2018), microstate review](https://doi.org/10.1016/j.neuroimage.2017.11.062)
diff --git a/skills/neurokit2/references/emg.md b/skills/neurokit2/references/emg.md
index 9e76437d..d6410b52 100644
--- a/skills/neurokit2/references/emg.md
+++ b/skills/neurokit2/references/emg.md
@@ -1,408 +1,157 @@
-# Electromyography (EMG) Analysis
+# Electromyography
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official EMG API, and human surface-EMG guidance.
-Electromyography (EMG) measures electrical activity produced by skeletal muscles during contraction. EMG analysis in NeuroKit2 focuses on amplitude estimation, muscle activation detection, and temporal dynamics for psychophysiology and motor control research.
+## Acquisition contract
-## Main Processing Pipeline
+Record muscle and task, electrode type/size/orientation/inter-electrode distance,
+reference, skin preparation, amplifier gain/range, hardware filters, unit, sampling
+rate, synchronization, posture/contraction, and artifact annotations. Follow a
+muscle-specific placement protocol such as SENIAM when applicable.
-### emg_process()
+EMG amplitude depends on geometry, subcutaneous tissue, cross-talk, electrode contact,
+hardware, and contraction history. It is not a direct universal force scale.
-Automated EMG signal processing pipeline.
+## Stable processing pipeline
```python
-signals, info = nk.emg_process(emg_signal, sampling_rate=1000)
+signals, info = nk.emg_process(emg, sampling_rate=1000)
```
-**Pipeline steps:**
-1. Signal cleaning (high-pass filtering, detrending)
-2. Amplitude envelope extraction
-3. Muscle activation detection
-4. Onset and offset identification
+Pinned 0.2.13 default columns:
-**Returns:**
-- `signals`: DataFrame with:
- - `EMG_Clean`: Filtered EMG signal
- - `EMG_Amplitude`: Linear envelope (smoothed rectified signal)
- - `EMG_Activity`: Binary activation indicator (0/1)
- - `EMG_Onsets`: Activation onset markers
- - `EMG_Offsets`: Activation offset markers
-- `info`: Dictionary with activation parameters
-
-**Typical workflow:**
-- Process raw EMG → Extract amplitude → Detect activations → Analyze features
-
-## Preprocessing Functions
-
-### emg_clean()
-
-Apply filtering to remove noise and prepare for amplitude extraction.
-
-```python
-cleaned_emg = nk.emg_clean(emg_signal, sampling_rate=1000)
+```text
+EMG_Raw, EMG_Clean, EMG_Amplitude,
+EMG_Activity, EMG_Onsets, EMG_Offsets
```
-**Filtering approach (BioSPPy method):**
-- Fourth-order Butterworth high-pass filter (100 Hz)
-- Removes low-frequency movement artifacts and baseline drift
-- Removes DC offset
-- Signal detrending
-
-**Rationale:**
-- EMG frequency content: 20-500 Hz (dominant: 50-150 Hz)
-- High-pass at 100 Hz isolates muscle activity
-- Removes ECG contamination (especially in trunk muscles)
-- Removes motion artifacts (<20 Hz)
+`info` contained event-level `EMG_Activity`, `EMG_Onsets`, `EMG_Offsets`, and
+`sampling_rate`. This is a default observation, not a universal schema.
-**EMG signal characteristics:**
-- Random, zero-mean oscillations during contraction
-- Higher amplitude = stronger contraction
-- Raw EMG: both positive and negative deflections
-
-## Feature Extraction
-
-### emg_amplitude()
-
-Compute linear envelope representing muscle contraction intensity.
+## Cleaning and amplitude
```python
-amplitude = nk.emg_amplitude(cleaned_emg, sampling_rate=1000)
+clean = nk.emg_clean(emg, sampling_rate=1000, method="biosppy")
+amplitude = nk.emg_amplitude(clean)
```
-**Method:**
-1. Full-wave rectification (absolute value)
-2. Low-pass filtering (smooth envelope)
-3. Downsampling (optional)
+Important stable details:
-**Linear envelope:**
-- Smooth curve following EMG amplitude modulation
-- Represents muscle force/activation level
-- Suitable for further analysis (activation detection, integration)
+- `emg_clean()` currently offers `biosppy` and `none`.
+- The BioSPPy path uses a fourth-order 100 Hz high-pass Butterworth filter followed by
+ constant detrending.
+- `emg_amplitude()` takes only the cleaned vector; it has no `sampling_rate` argument
+ in 0.2.13.
-**Typical smoothing:**
-- Low-pass filter: 10-20 Hz cutoff
-- Moving average: 50-200 ms window
-- Balance: responsiveness vs. smoothness
+A 100 Hz high-pass may be unsuitable for some surface-EMG endpoints and impossible at
+low sampling rates. Do not treat the package default as a universal acquisition
+standard. Set sampling rate above twice the highest retained frequency with transition
+band margin; surface EMG is commonly acquired around 1000–2000 Hz, but the study,
+hardware, muscle, and endpoint determine requirements.
-## Activation Detection
+## Activation detection
-### emg_activation()
+Stable signature:
-Detect periods of muscle activation (onsets and offsets).
-
-```python
-activity, info = nk.emg_activation(emg_amplitude, sampling_rate=1000, method='threshold',
- threshold='auto', duration_min=0.05)
+```text
+emg_activation(
+ emg_amplitude=None, emg_cleaned=None, sampling_rate=1000,
+ method="threshold", threshold="default", duration_min="default",
+ size=None, threshold_size=None, **kwargs
+)
```
-**Methods:**
+Use the correct input for the method:
-**1. Threshold-based (default):**
-```python
-activity = nk.emg_activation(amplitude, method='threshold', threshold='auto')
-```
-- Compares amplitude to threshold
-- `threshold='auto'`: Automatic based on signal statistics (e.g., mean + 1 SD)
-- `threshold=0.1`: Manual absolute threshold
-- Simple, fast, widely used
-
-**2. Gaussian Mixture Model (GMM):**
-```python
-activity = nk.emg_activation(amplitude, method='mixture', n_clusters=2)
-```
-- Unsupervised clustering: active vs. rest
-- Adaptive to signal characteristics
-- More robust to varying baseline
+- `threshold` or `mixture`: pass `emg_amplitude`;
+- `pelt`, `biosppy`, or `silva`: pass `emg_cleaned`.
-**3. Changepoint detection:**
```python
-activity = nk.emg_activation(amplitude, method='changepoint')
+activity_signals, activity_info = nk.emg_activation(
+ emg_amplitude=amplitude,
+ sampling_rate=1000,
+ method="threshold",
+ threshold="default",
+ duration_min=0.05,
+)
```
-- Detects abrupt transitions in signal properties
-- Identifies activation/deactivation points
-- Useful for complex temporal patterns
-**4. Bimodality (Silva et al., 2013):**
-```python
-activity = nk.emg_activation(amplitude, method='bimodal')
-```
-- Tests for bimodal distribution (active vs. rest)
-- Determines optimal separation threshold
-- Statistically principled
+Return order is `(activity_signals, info)`. The DataFrame has same-length
+`EMG_Activity`, `EMG_Onsets`, and `EMG_Offsets`; the dict contains event indices.
+`duration_min` is seconds. `size` semantics are method-specific.
-**Key parameters:**
-- `duration_min`: Minimum activation duration (seconds)
- - Filters brief spurious activations
- - Typical: 50-100 ms
-- `threshold`: Activation threshold (method-dependent)
+Automatic thresholds are hypotheses, not ground truth. Tune/validate on independent
+labeled contractions or a prespecified baseline. Report threshold, window, smoothing,
+minimum duration, and false/missed activation performance.
-**Returns:**
-- `activity`: Binary array (0 = rest, 1 = active)
-- `info`: Dictionary with onset/offset indices
+## Missing data and artifacts
-**Activation metrics:**
-- **Onset**: Transition from rest to activity
-- **Offset**: Transition from activity to rest
-- **Duration**: Time between onset and offset
-- **Burst**: Single period of continuous activation
+Inspect and annotate:
-## Analysis Functions
+- clipping/saturation and disconnected/flat channels;
+- motion/cable artifacts and low-frequency transients;
+- powerline interference;
+- ECG contamination, especially trunk/proximal sites;
+- cross-talk from adjacent muscles; and
+- baseline changes from contact/sweat.
-### emg_analyze()
+Do not interpolate across a burst or activation onset. Segment long gaps, preserve a
+validity mask, and reject affected trials/windows under prespecified rules. Filtering
+cannot establish that a deflection came from the target muscle.
-Automatically select event-related or interval-related analysis.
+## Event and interval features
```python
-analysis = nk.emg_analyze(signals, sampling_rate=1000)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=1000,
+ epochs_start=-0.1,
+ epochs_end=1.0,
+ baseline_correction=False,
+)
+event_features = nk.emg_eventrelated(epochs)
+interval_features = nk.emg_intervalrelated(signals)
```
-**Mode selection:**
-- Duration < 10 seconds → event-related
-- Duration ≥ 10 seconds → interval-related
+Documented event-related features include `EMG_Activation`,
+`EMG_Amplitude_Mean`, `EMG_Amplitude_Max`, `EMG_Amplitude_SD`,
+`EMG_Amplitude_Max_Time`, and `EMG_Bursts`. Interval analysis returns
+`EMG_Activation_N` and `EMG_Amplitude_Mean` in the pinned official example.
+Columns are conditional; inspect output.
-### emg_eventrelated()
+For startle or rapid onset work, hardware latency, synchronization, filter group delay,
+rectification/smoothing, and onset-definition error can dominate the result.
-Analyze EMG responses to discrete events/stimuli.
+## Normalization
-```python
-results = nk.emg_eventrelated(epochs)
-```
-
-**Computed metrics (per epoch):**
-- `EMG_Activation`: Presence of activation (binary)
-- `EMG_Amplitude_Mean`: Average amplitude during epoch
-- `EMG_Amplitude_Max`: Peak amplitude
-- `EMG_Bursts`: Number of activation bursts
-- `EMG_Onset_Latency`: Time from event to first activation (if applicable)
+Raw/envelope amplitude is usually not comparable across participants or sessions.
+Possible denominators include MVC, reference contraction, or within-participant
+standardization, but each changes the estimand.
-**Use cases:**
-- Startle response (orbicularis oculi EMG)
-- Facial EMG during emotional stimuli (corrugator, zygomaticus)
-- Motor response latencies
-- Muscle reactivity paradigms
+If using MVC:
-### emg_intervalrelated()
+- acquire it with a validated, safe protocol;
+- inspect fatigue, pain, effort, clipping, and target/cross-talk;
+- define which statistic and window represent MVC;
+- report repetitions and reliability; and
+- never divide by a near-zero/invalid reference.
-Analyze extended EMG recordings.
-
-```python
-results = nk.emg_intervalrelated(signals, sampling_rate=1000)
-```
+Normalization does not make electrode/site differences disappear.
-**Computed metrics:**
-- `EMG_Bursts_N`: Total number of activation bursts
-- `EMG_Amplitude_Mean`: Mean amplitude across entire interval
-- `EMG_Activation_Duration`: Total time in active state
-- `EMG_Rest_Duration`: Total time in rest state
+## Interpretation boundary
-**Use cases:**
-- Resting muscle tension assessment
-- Chronic pain or stress-related muscle activity
-- Fatigue monitoring during sustained tasks
-- Postural muscle assessment
+NeuroKit2 EMG can support research on amplitude and detected activity. It does not
+provide validated motor-unit decomposition, neuromuscular diagnosis, fatigue
+monitoring, prosthetic control safety, rehabilitation decisions, or sleep scoring.
+Those require endpoint-specific acquisition, algorithms, standards, and independent
+validation.
-## Simulation and Visualization
-
-### emg_simulate()
-
-Generate synthetic EMG signals for testing.
-
-```python
-synthetic_emg = nk.emg_simulate(duration=10, sampling_rate=1000, burst_number=3,
- noise=0.1, random_state=42)
-```
-
-**Parameters:**
-- `burst_number`: Number of activation bursts to include
-- `noise`: Background noise level
-- `random_state`: Reproducibility seed
-
-**Generated features:**
-- Random EMG-like oscillations during bursts
-- Realistic frequency content
-- Variable burst timing and amplitude
-
-**Use cases:**
-- Algorithm validation
-- Detection parameter tuning
-- Educational demonstrations
-
-### emg_plot()
-
-Visualize processed EMG signal.
-
-```python
-nk.emg_plot(signals, info, static=True)
-```
-
-**Displays:**
-- Raw and cleaned EMG signal
-- Amplitude envelope
-- Detected activation periods
-- Onset/offset markers
-
-**Interactive mode:** Set `static=False` for Plotly visualization
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 500 Hz (Nyquist for 250 Hz upper frequency)
-- **Standard**: 1000 Hz (most research applications)
-- **High-resolution**: 2000-4000 Hz (detailed motor unit studies)
-- **Surface EMG**: 1000-2000 Hz typical
-- **Intramuscular EMG**: 10,000+ Hz for single motor units
-
-### Recording Duration
-- **Event-related**: Depends on paradigm (e.g., 2-5 seconds per trial)
-- **Sustained contraction**: Seconds to minutes
-- **Fatigue studies**: Minutes to hours
-- **Chronic monitoring**: Days (wearable EMG)
-
-### Electrode Placement
-
-**Surface EMG (most common):**
-- Bipolar configuration (two electrodes over muscle belly)
-- Reference/ground electrode over electrically neutral site (bone)
-- Skin preparation: clean, abrade, reduce impedance
-- Inter-electrode distance: 10-20 mm (SENIAM standards)
-
-**Muscle-specific guidelines:**
-- Follow SENIAM (Surface EMG for Non-Invasive Assessment of Muscles) recommendations
-- Palpate muscle during contraction to locate belly
-- Align electrodes with muscle fiber direction
-
-**Common muscles in psychophysiology:**
-- **Corrugator supercilii**: Frowning, negative affect (above eyebrow)
-- **Zygomaticus major**: Smiling, positive affect (cheek)
-- **Orbicularis oculi**: Startle response, fear (around eye)
-- **Masseter**: Jaw clenching, stress (jaw muscle)
-- **Trapezius**: Shoulder tension, stress (upper back)
-- **Frontalis**: Forehead tension, surprise
-
-### Signal Quality Issues
-
-**ECG contamination:**
-- Common in trunk and proximal muscles
-- High-pass filtering (>100 Hz) usually sufficient
-- If persistent: template subtraction, ICA
-
-**Motion artifacts:**
-- Low-frequency disturbances
-- Electrode cable movement
-- Secure electrodes, minimize cable motion
-
-**Electrode issues:**
-- Poor contact: high impedance, low amplitude
-- Sweat: gradual amplitude increase, instability
-- Hair: clean or shave area
-
-**Cross-talk:**
-- Adjacent muscle activity bleeding into recording
-- Careful electrode placement
-- Small inter-electrode distance
-
-### Best Practices
-
-**Standard workflow:**
-```python
-# 1. Clean signal (high-pass filter, detrend)
-cleaned = nk.emg_clean(emg_raw, sampling_rate=1000)
-
-# 2. Extract amplitude envelope
-amplitude = nk.emg_amplitude(cleaned, sampling_rate=1000)
-
-# 3. Detect activation periods
-activity, info = nk.emg_activation(amplitude, sampling_rate=1000,
- method='threshold', threshold='auto')
-
-# 4. Comprehensive processing (alternative)
-signals, info = nk.emg_process(emg_raw, sampling_rate=1000)
-
-# 5. Analyze
-analysis = nk.emg_analyze(signals, sampling_rate=1000)
-```
-
-**Normalization:**
-```python
-# Maximum voluntary contraction (MVC) normalization
-mvc_amplitude = np.max(mvc_emg_amplitude) # From separate MVC trial
-normalized_emg = (amplitude / mvc_amplitude) * 100 # Express as % MVC
-
-# Common in ergonomics, exercise physiology
-# Allows comparison across individuals and sessions
-```
+## Sources checked 2026-07-23
-## Clinical and Research Applications
-
-**Psychophysiology:**
-- **Facial EMG**: Emotional valence (smile vs. frown)
-- **Startle response**: Fear, surprise, defensive reactivity
-- **Stress**: Chronic muscle tension (trapezius, masseter)
-
-**Motor control and rehabilitation:**
-- Gait analysis
-- Movement disorders (tremor, dystonia)
-- Stroke rehabilitation (muscle re-activation)
-- Prosthetic control (myoelectric)
-
-**Ergonomics and occupational health:**
-- Work-related musculoskeletal disorders
-- Postural assessment
-- Repetitive strain injury risk
-
-**Sports science:**
-- Muscle activation patterns during exercise
-- Fatigue assessment (median frequency shift)
-- Training optimization
-
-**Biofeedback:**
-- Relaxation training (reduce muscle tension)
-- Neuromuscular re-education
-- Chronic pain management
-
-**Sleep medicine:**
-- Chin EMG for REM sleep atonia
-- Periodic limb movements
-- Bruxism (teeth grinding)
-
-## Advanced EMG Analysis (Beyond NeuroKit2 Basic Functions)
-
-**Frequency domain:**
-- Median frequency shift during fatigue
-- Power spectrum analysis
-- Requires longer segments (≥1 second per analysis window)
-
-**Motor unit identification:**
-- Intramuscular EMG
-- Spike detection and sorting
-- Firing rate analysis
-- Requires high sampling rates (10+ kHz)
-
-**Muscle coordination:**
-- Co-contraction indices
-- Synergy analysis
-- Multi-muscle integration
-
-## Interpretation Guidelines
-
-**Amplitude (linear envelope):**
-- Higher amplitude ≈ stronger contraction (not perfectly linear)
-- Relationship to force: sigmoid, influenced by many factors
-- Within-subject comparisons most reliable
-
-**Activation threshold:**
-- Automatic thresholds: convenient but verify visually
-- Manual thresholds: may be needed for non-standard muscles
-- Resting baseline: should be near zero (if not, check electrodes)
-
-**Burst characteristics:**
-- **Phasic**: Brief bursts (startle, rapid movements)
-- **Tonic**: Sustained activation (postural, sustained grip)
-- **Rhythmic**: Repeated bursts (tremor, walking)
-
-## References
-
-- Fridlund, A. J., & Cacioppo, J. T. (1986). Guidelines for human electromyographic research. Psychophysiology, 23(5), 567-589.
-- Hermens, H. J., Freriks, B., Disselhorst-Klug, C., & Rau, G. (2000). Development of recommendations for SEMG sensors and sensor placement procedures. Journal of electromyography and Kinesiology, 10(5), 361-374.
-- Silva, H., Scherer, R., Sousa, J., & Londral, A. (2013). Towards improving the ssability of electromyographic interfaces. Journal of Oral Rehabilitation, 40(6), 456-465.
-- Tassinary, L. G., Cacioppo, J. T., & Vanman, E. J. (2017). The skeletomotor system: Surface electromyography. In Handbook of psychophysiology (pp. 267-299). Cambridge University Press.
+- [Official EMG API](https://neuropsychology.github.io/NeuroKit/functions/emg.html)
+- [Stable v0.2.13 EMG source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/emg)
+- [Fridlund & Cacioppo (1986), human EMG guidelines](https://pubmed.ncbi.nlm.nih.gov/3809364/)
+- [Hermens et al. (2000), SENIAM sensor/placement recommendations](https://doi.org/10.1016/S1050-6411(00)00027-4)
+- [Blumenthal et al. (2005), startle eyeblink EMG guidelines](https://doi.org/10.1111/j.1469-8986.2005.00271.x)
diff --git a/skills/neurokit2/references/eog.md b/skills/neurokit2/references/eog.md
index 9599f8ae..2c37c999 100644
--- a/skills/neurokit2/references/eog.md
+++ b/skills/neurokit2/references/eog.md
@@ -1,407 +1,154 @@
-# Electrooculography (EOG) Analysis
+# Electrooculography
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable source/runtime
+and the official EOG API/example.
-Electrooculography (EOG) measures eye movements and blinks by detecting electrical potential differences generated by eye position changes. EOG is used in sleep studies, attention research, reading analysis, and artifact correction for EEG.
+## Scope and orientation
-## Main Processing Pipeline
+NeuroKit2's EOG pipeline is primarily a **vertical EOG blink** workflow. Stable
+`eog_process()` requires blinks to be positive-going peaks. Verify channel montage,
+polarity, reference, physical unit, sampling rate, hardware filters, amplifier range,
+clock, and synchronization before processing.
-### eog_process()
+Do not use this module as a full gaze, saccade, fixation, or sleep-scoring system.
+Horizontal/vertical eye-movement interpretation and clinical/drowsiness monitoring need
+separate validated methods.
-Automated EOG signal processing pipeline.
+## Optional MNE default
-```python
-signals, info = nk.eog_process(eog_signal, sampling_rate=500, method='neurokit')
-```
-
-**Pipeline steps:**
-1. Signal cleaning (filtering)
-2. Blink detection
-3. Blink rate calculation
-
-**Returns:**
-- `signals`: DataFrame with:
- - `EOG_Clean`: Filtered EOG signal
- - `EOG_Blinks`: Binary blink markers (0/1)
- - `EOG_Rate`: Instantaneous blink rate (blinks/min)
-- `info`: Dictionary with blink indices and parameters
-
-**Methods:**
-- `'neurokit'`: NeuroKit2 optimized approach (default)
-- `'agarwal2019'`: Agarwal et al. (2019) algorithm
-- `'mne'`: MNE-Python method
-- `'brainstorm'`: Brainstorm toolbox approach
-- `'kong1998'`: Kong et al. (1998) method
-
-## Preprocessing Functions
-
-### eog_clean()
-
-Prepare raw EOG signal for blink detection.
+`eog_peaks()` and `eog_findpeaks()` default to `method="mne"`. In the core 0.2.13
+installation, MNE is optional; the default can therefore raise an ImportError. Either
+add MNE at a reviewed exact version to the project lock or choose a core method:
```python
-cleaned_eog = nk.eog_clean(eog_signal, sampling_rate=500, method='neurokit')
+signals, info = nk.eog_process(
+ veog,
+ sampling_rate=200,
+ method="neurokit",
+)
```
-**Methods:**
-- `'neurokit'`: Butterworth filtering optimized for EOG
-- `'agarwal2019'`: Alternative filtering
-- `'mne'`: MNE-Python preprocessing
-- `'brainstorm'`: Brainstorm approach
-- `'kong1998'`: Kong's method
+`eog_process()` forwards `**kwargs` to cleaning and peak finding. Record the explicit
+method rather than relying on an environment-dependent default.
-**Typical filtering:**
-- Low-pass: 10-20 Hz (remove high-frequency noise)
-- High-pass: 0.1-1 Hz (remove DC drift)
-- Preserves blink waveform (typical duration 100-400 ms)
+## Stable schemas
-**EOG signal characteristics:**
-- **Blinks**: Large amplitude, stereotyped waveform (200-400 ms)
-- **Saccades**: Rapid step-like deflections (20-80 ms)
-- **Smooth pursuit**: Slow ramp-like changes
-- **Baseline**: Stable when eyes fixated
+The high-level return is `(signals, info)`. Default columns are:
-## Blink Detection
-
-### eog_peaks()
-
-Detect eye blinks in EOG signal.
-
-```python
-blinks, info = nk.eog_peaks(cleaned_eog, sampling_rate=500, method='neurokit',
- threshold=0.33)
+```text
+EOG_Raw, EOG_Clean, EOG_Blinks, EOG_Rate
```
-**Methods:**
-- `'neurokit'`: Amplitude and duration criteria (default)
-- `'mne'`: MNE-Python blink detection
-- `'brainstorm'`: Brainstorm approach
-- `'blinker'`: BLINKER algorithm (Kleifges et al., 2017)
-
-**Key parameters:**
-- `threshold`: Amplitude threshold (fraction of max amplitude)
- - Typical: 0.2-0.5
- - Lower: more sensitive (may include false positives)
- - Higher: more conservative (may miss small blinks)
-
-**Returns:**
-- Dictionary with `'EOG_Blinks'` key containing blink peak indices
-
-**Blink characteristics:**
-- **Frequency**: 15-20 blinks/min (resting, comfortable)
-- **Duration**: 100-400 ms (mean ~200 ms)
-- **Amplitude**: Varies with electrode placement and individual factors
-- **Waveform**: Biphasic or triphasic
-
-### eog_findpeaks()
-
-Low-level blink detection with multiple algorithms.
-
-```python
-blinks_dict = nk.eog_findpeaks(cleaned_eog, sampling_rate=500, method='neurokit')
-```
-
-**Use cases:**
-- Custom parameter tuning
-- Algorithm comparison
-- Research method development
-
-## Feature Extraction
-
-### eog_features()
-
-Extract characteristics of individual blinks.
-
-```python
-features = nk.eog_features(signals, sampling_rate=500)
-```
-
-**Computed features:**
-- **Amplitude velocity ratio (AVR)**: Peak velocity / amplitude
- - Discriminates blinks from artifacts
-- **Blink-amplitude ratio**: Consistency of blink amplitudes
-- **Duration metrics**: Blink duration statistics (mean, SD)
-- **Peak amplitude**: Maximum deflection
-- **Peak velocity**: Maximum rate of change
-
-**Use cases:**
-- Blink quality assessment
-- Drowsiness detection (blink duration increases when sleepy)
-- Neurological assessment (altered blink dynamics in disease)
+`info` has `EOG_Blinks` (sample indices) and `sampling_rate`.
-### eog_rate()
-
-Compute blink frequency (blinks per minute).
+Low-level interfaces differ:
```python
-blink_rate = nk.eog_rate(blinks, sampling_rate=500, desired_length=None)
+clean = nk.eog_clean(veog, sampling_rate=200, method="neurokit")
+
+# Returns only an array of blink sample indices.
+blink_indices = nk.eog_findpeaks(
+ clean,
+ sampling_rate=200,
+ method="neurokit",
+)
+
+# Returns (same-length marker DataFrame, info dict).
+blink_markers, blink_info = nk.eog_peaks(
+ clean,
+ sampling_rate=200,
+ method="neurokit",
+)
```
-**Method:**
-- Calculate inter-blink intervals
-- Convert to blinks per minute
-- Interpolate to match signal length
-
-**Typical blink rates:**
-- **Resting**: 15-20 blinks/min
-- **Reading/visual tasks**: 5-10 blinks/min (suppressed)
-- **Conversation**: 20-30 blinks/min
-- **Stress/dry eyes**: >30 blinks/min
-- **Drowsiness**: Variable, longer blinks
+The 0.2.13 `eog_peaks()` docstring return section says array, while its tagged source
+returns `(signals, info)`. The pinned source/runtime is authoritative for stable work.
-## Analysis Functions
+Stable cleaning methods include `neurokit`, `agarwal2019`, `mne`, `brainstorm`, and
+`kong1998`. Peak methods include `neurokit`, `mne`, `brainstorm`, and `blinker`.
+MNE and some method paths need optional dependencies.
-### eog_analyze()
-
-Automatically select event-related or interval-related analysis.
+## Blink features
```python
-analysis = nk.eog_analyze(signals, sampling_rate=500)
+features = nk.eog_features(
+ clean,
+ blink_info["EOG_Blinks"],
+ sampling_rate=200,
+)
```
-**Mode selection:**
-- Duration < 10 seconds → event-related
-- Duration ≥ 10 seconds → interval-related
-
-### eog_eventrelated()
+`eog_features()` needs both the cleaned signal and peak-index array. It returns a dict
+with event-level fields such as:
-Analyze blink patterns relative to specific events.
-
-```python
-results = nk.eog_eventrelated(epochs)
+```text
+Blink_LeftZeros, Blink_RightZeros, Blink_pAVR,
+Blink_nAVR, Blink_BAR, Blink_Duration
```
-**Computed metrics (per epoch):**
-- `EOG_Blinks_N`: Number of blinks during epoch
-- `EOG_Rate_Mean`: Average blink rate
-- `EOG_Blink_Presence`: Binary (any blinks occurred)
-- Temporal distribution of blinks across epoch
+Do not pass the processed DataFrame as the only argument. Feature validity depends on
+positive orientation and accurate blink segmentation.
-**Use cases:**
-- Blink-locked ERP contamination assessment
-- Attention and engagement during stimuli
-- Visual task difficulty (suppressed blinks during demanding tasks)
-- Spontaneous blinks after stimulus offset
+## Sampling and artifacts
-### eog_intervalrelated()
+Choose a rate from the endpoint and hardware bandwidth, not a universal number. Basic
+blink timing may use lower rates than detailed eyelid velocity or saccade morphology.
+Validate temporal error against labeled data at the actual rate; 200–500 Hz is common
+in research but not a guarantee.
-Analyze blink patterns over extended periods.
+Inspect:
-```python
-results = nk.eog_intervalrelated(signals, sampling_rate=500)
-```
+- saturation and clipping during large eye movements;
+- baseline drift and electrode polarization;
+- frontal/facial EMG and movement/cable artifacts;
+- line noise and channel detachment;
+- polarity and montage changes across sessions; and
+- missing samples and synchronization with EEG/events.
-**Computed metrics:**
-- `EOG_Blinks_N`: Total number of blinks
-- `EOG_Rate_Mean`: Average blink rate (blinks/min)
-- `EOG_Rate_SD`: Blink rate variability
-- `EOG_Duration_Mean`: Average blink duration (if available)
-- `EOG_Amplitude_Mean`: Average blink amplitude (if available)
+Do not interpolate through a blink or across detachment. Preserve raw/clean overlays,
+blink markers, rejected segments, and manual review outcomes.
-**Use cases:**
-- Resting state blink patterns
-- Drowsiness or fatigue monitoring (increased duration)
-- Sustained attention tasks (suppressed rate)
-- Dry eye assessment (increased rate, incomplete blinks)
-
-## Simulation and Visualization
-
-### eog_plot()
-
-Visualize processed EOG signal and detected blinks.
+## Event and interval analysis
```python
-nk.eog_plot(signals, info)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=200,
+ epochs_start=-0.5,
+ epochs_end=2,
+ baseline_correction=False,
+)
+event_features = nk.eog_eventrelated(epochs)
+interval_features = nk.eog_intervalrelated(signals)
```
-**Displays:**
-- Raw and cleaned EOG signal
-- Detected blink markers
-- Blink rate time course
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 100 Hz (basic blink detection)
-- **Standard**: 250-500 Hz (research applications)
-- **High-resolution**: 1000 Hz (detailed waveform analysis, saccades)
-- **Sleep studies**: 200-250 Hz typical
-
-### Recording Duration
-- **Blink detection**: Any duration (≥1 blink)
-- **Blink rate estimation**: ≥60 seconds for stable estimate
-- **Event-related**: Depends on paradigm (seconds per trial)
-- **Sleep EOG**: Hours (full night)
-
-### Electrode Placement
+Documented event-related fields include `EOG_Rate_Baseline`, rate min/max/mean/SD and
+times, plus `EOG_Blinks_Presence`. Interval analysis returns `EOG_Peaks_N` and
+`EOG_Rate_Mean` in the official example. It does not universally return blink
+amplitude or duration summaries. Inspect columns at runtime.
-**Standard configurations:**
+Blink rate over short windows is unstable and task-dependent. A count/rate change does
+not uniquely identify attention, fatigue, stress, dry eye, dopamine, or a neurological
+condition.
-**Horizontal EOG (HEOG):**
-- Two electrodes: lateral canthi (outer corners) of left and right eyes
-- Measures horizontal eye movements (saccades, smooth pursuit)
-- Bipolar recording (left - right)
+## EEG integration
-**Vertical EOG (VEOG):**
-- Two electrodes: above and below one eye (typically right)
-- Measures vertical eye movements and blinks
-- Bipolar recording (above - below)
+EOG can help identify ocular contamination in EEG, but NeuroKit2 does not provide a
+complete validated correction pipeline here. With MNE:
-**Sleep EOG:**
-- Often uses slightly different placement (temple area)
-- E1: 1 cm lateral and 1 cm below outer canthus of left eye
-- E2: 1 cm lateral and 1 cm above outer canthus of right eye
-- Captures both horizontal and vertical movements
+1. synchronize and preserve dedicated EOG channels;
+2. fit artifact identification/correction on appropriate data;
+3. verify component or regression selection without removing neural signal;
+4. compare raw and corrected ERPs/spectra/topographies; and
+5. report method, channels, filters, thresholds, components, and exclusions.
-**EEG contamination removal:**
-- Frontal electrodes (Fp1, Fp2) can serve as EOG proxies
-- ICA-based EOG artifact removal common in EEG preprocessing
+Avoid circularly selecting correction settings to maximize an experimental result.
-### Common Issues and Solutions
-
-**Electrode issues:**
-- Poor contact: low amplitude, noise
-- Skin preparation: clean, light abrasion
-- Conductive gel: ensure good contact
-
-**Artifacts:**
-- Muscle activity (especially frontalis): high-frequency noise
-- Movement: cable artifacts, head motion
-- Electrical noise: 50/60 Hz hum (ground properly)
-
-**Saturation:**
-- Large saccades may saturate amplifier
-- Adjust gain or voltage range
-- More common with low-resolution systems
-
-### Best Practices
-
-**Standard workflow:**
-```python
-# 1. Clean signal
-cleaned = nk.eog_clean(eog_raw, sampling_rate=500, method='neurokit')
-
-# 2. Detect blinks
-blinks, info = nk.eog_peaks(cleaned, sampling_rate=500, method='neurokit')
-
-# 3. Extract features
-features = nk.eog_features(signals, sampling_rate=500)
-
-# 4. Comprehensive processing (alternative)
-signals, info = nk.eog_process(eog_raw, sampling_rate=500)
-
-# 5. Analyze
-analysis = nk.eog_analyze(signals, sampling_rate=500)
-```
-
-**EEG artifact correction workflow:**
-```python
-# Option 1: Regression-based removal
-# Identify EOG components from cleaned EOG signal
-# Regress out EOG from EEG channels
-
-# Option 2: ICA-based removal (preferred)
-# 1. Run ICA on EEG data including EOG channels
-# 2. Identify ICA components correlated with EOG
-# 3. Remove EOG components from EEG data
-# NeuroKit2 integrates with MNE for this workflow
-```
+## Sources checked 2026-07-23
-## Clinical and Research Applications
-
-**EEG artifact correction:**
-- Blinks contaminate frontal EEG channels
-- ICA or regression methods remove EOG artifacts
-- Essential for ERP studies
-
-**Sleep staging:**
-- Rapid eye movements (REMs) during REM sleep
-- Slow rolling eye movements during drowsiness
-- Sleep onset and stage transitions
-
-**Attention and cognitive load:**
-- Blink rate suppressed during demanding tasks
-- Blinks cluster at task boundaries (natural breakpoints)
-- Spontaneous blink as indicator of attention shifts
-
-**Fatigue and drowsiness monitoring:**
-- Increased blink duration when sleepy
-- Slower eyelid closures
-- Partial or incomplete blinks
-- Driver monitoring applications
-
-**Reading and visual processing:**
-- Blinks suppressed during reading
-- Eye movements during saccades (line changes)
-- Fatigue effects on reading efficiency
-
-**Neurological disorders:**
-- **Parkinson's disease**: Reduced spontaneous blink rate
-- **Schizophrenia**: Increased blink rate
-- **Tourette syndrome**: Excessive blinking (tics)
-- **Dry eye syndrome**: Increased, incomplete blinks
-
-**Affective and social cognition:**
-- Blink synchrony in social interaction
-- Emotional modulation of blink rate
-- Blink-related potentials in ERPs
-
-**Human-computer interaction:**
-- Gaze tracking preprocessing
-- Attention monitoring
-- User engagement assessment
-
-## Eye Movement Types Detectable with EOG
-
-**Blinks:**
-- Large amplitude, brief duration (100-400 ms)
-- NeuroKit2 primary focus
-- Vertical EOG most sensitive
-
-**Saccades:**
-- Rapid, ballistic eye movements (20-80 ms)
-- Step-like voltage deflections
-- Horizontal or vertical
-- Require higher sampling rates for detailed analysis
-
-**Smooth pursuit:**
-- Slow tracking of moving objects
-- Ramp-like voltage changes
-- Lower amplitude than saccades
-
-**Fixations:**
-- Stable gaze
-- Baseline EOG with small oscillations
-- Duration varies (200-600 ms typical in reading)
-
-**Note:** Detailed saccade/fixation analysis typically requires eye tracking (infrared, video-based). EOG useful for blinks and gross eye movements.
-
-## Interpretation Guidelines
-
-**Blink rate:**
-- **Normal resting**: 15-20 blinks/min
-- **<10 blinks/min**: Visual task engagement, concentration
-- **>30 blinks/min**: Stress, dry eyes, fatigue
-- **Context-dependent**: Task demands, lighting, screen use
-
-**Blink duration:**
-- **Normal**: 100-400 ms (mean ~200 ms)
-- **Prolonged**: Drowsiness, fatigue (>500 ms)
-- **Short**: Normal alertness
-
-**Blink amplitude:**
-- Varies with electrode placement and individuals
-- Within-subject comparisons most reliable
-- Incomplete blinks: reduced amplitude (dry eye, fatigue)
-
-**Temporal patterns:**
-- **Clustered blinks**: Transitions between tasks or cognitive states
-- **Suppressed blinks**: Active visual processing, sustained attention
-- **Post-stimulus blinks**: After completing visual processing
-
-## References
-
-- Kleifges, K., Bigdely-Shamlo, N., Kerick, S. E., & Robbins, K. A. (2017). BLINKER: Automated extraction of ocular indices from EEG enabling large-scale analysis. Frontiers in Neuroscience, 11, 12.
-- Agarwal, M., & Sivakumar, R. (2019). Blink: A fully automated unsupervised algorithm for eye-blink detection in EEG signals. In 2019 57th Annual Allerton Conference on Communication, Control, and Computing (pp. 1113-1121). IEEE.
-- Kong, X., & Wilson, G. F. (1998). A new EOG-based eyeblink detection algorithm. Behavior Research Methods, Instruments, & Computers, 30(4), 713-719.
-- Schleicher, R., Galley, N., Briest, S., & Galley, L. (2008). Blinks and saccades as indicators of fatigue in sleepiness warnings: Looking tired? Ergonomics, 51(7), 982-1010.
+- [Official EOG API](https://neuropsychology.github.io/NeuroKit/functions/eog.html)
+- [Official EOG example](https://neuropsychology.github.io/NeuroKit/examples/eog_analyze/eog_analyze.html)
+- [Stable v0.2.13 EOG source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/eog)
+- [Kleifges et al. (2017), BLINKER](https://doi.org/10.3389/fnins.2017.00012)
+- [Keil et al. (2014), EEG/MEG reporting guidance](https://doi.org/10.1111/psyp.12147)
diff --git a/skills/neurokit2/references/epochs_events.md b/skills/neurokit2/references/epochs_events.md
index 1816f02b..6fb179d8 100644
--- a/skills/neurokit2/references/epochs_events.md
+++ b/skills/neurokit2/references/epochs_events.md
@@ -1,471 +1,199 @@
-# Epochs and Event-Related Analysis
+# Events and epochs
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable source/runtime and
+the live Events and Epochs API pages.
-Event-related analysis examines physiological responses time-locked to specific stimuli or events. NeuroKit2 provides tools for event detection, epoch creation, averaging, and event-related feature extraction across all signal types.
+## Event coordinate contract
-## Event Detection
+Choose one canonical representation before analysis:
-### events_find()
+- absolute time with a named clock and unit;
+- zero-based sample index on a named stream; and
+- event duration and condition/label metadata.
-Automatically detect events/triggers in a signal based on threshold crossings or changes.
+`events_find()` uses zero-based sample positions. Its `start_at`, `end_at`,
+`duration_min`, `duration_max`, and `inter_min` arguments are sample counts, not
+seconds.
```python
-events = nk.events_find(event_channel, threshold=0.5, threshold_keep='above',
- duration_min=1, inter_min=0)
+events = nk.events_find(
+ trigger,
+ threshold=0.5,
+ threshold_keep="above",
+ duration_min=2,
+ inter_min=5,
+ event_conditions=["A", "B", "A"],
+)
```
-**Parameters:**
-- `threshold`: Detection threshold value
-- `threshold_keep`: `'above'` or `'below'` threshold
-- `duration_min`: Minimum event duration (samples) to keep
-- `inter_min`: Minimum interval between events (samples)
+Stable signature:
-**Returns:**
-- Dictionary with:
- - `'onset'`: Event onset indices
- - `'offset'`: Event offset indices (if applicable)
- - `'duration'`: Event durations
- - `'label'`: Event labels (if multiple event types)
-
-**Common use cases:**
-
-**TTL triggers from experiments:**
-```python
-# Trigger channel: 0V baseline, 5V pulses during events
-events = nk.events_find(trigger_channel, threshold=2.5, threshold_keep='above')
-```
-
-**Button presses:**
-```python
-# Detect when button signal goes high
-button_events = nk.events_find(button_signal, threshold=0.5, threshold_keep='above',
- duration_min=10) # Debounce
-```
-
-**State changes:**
-```python
-# Detect periods above/below threshold
-high_arousal = nk.events_find(eda_signal, threshold='auto', duration_min=100)
-```
-
-### events_plot()
-
-Visualize event timing relative to signals.
-
-```python
-nk.events_plot(events, signal)
-```
-
-**Displays:**
-- Signal trace
-- Event markers (vertical lines or shaded regions)
-- Event labels
-
-**Use case:**
-- Verify event detection accuracy
-- Inspect temporal distribution of events
-- Quality control before epoching
-
-## Epoch Creation
-
-### epochs_create()
-
-Create epochs (segments) of data around events for event-related analysis.
-
-```python
-epochs = nk.epochs_create(data, events, sampling_rate=1000,
- epochs_start=-0.5, epochs_end=2.0,
- event_labels=None, event_conditions=None,
- baseline_correction=False)
+```text
+events_find(
+ event_channel, threshold="auto", threshold_keep="above",
+ start_at=0, end_at=None, duration_min=1, duration_max=None,
+ inter_min=0, discard_first=0, discard_last=0,
+ event_labels=None, event_conditions=None
+)
```
-**Parameters:**
-- `data`: DataFrame with signals or single signal
-- `events`: Event indices or dictionary from `events_find()`
-- `sampling_rate`: Signal sampling rate (Hz)
-- `epochs_start`: Start time relative to event (seconds, negative = before)
-- `epochs_end`: End time relative to event (seconds, positive = after)
-- `event_labels`: List of labels for each event (optional)
-- `event_conditions`: List of condition names for each event (optional)
-- `baseline_correction`: If True, subtract baseline mean from each epoch
-
-**Returns:**
-- Dictionary of DataFrames, one per epoch
-- Each DataFrame contains signal data with time relative to event (Index=0 at event onset)
-- Includes `'Label'` and `'Condition'` columns if provided
-
-**Typical epoch windows:**
-- **Visual ERP**: -0.2 to 1.0 seconds (200 ms baseline, 1 s post-stimulus)
-- **Cardiac orienting**: -1.0 to 10 seconds (capture anticipation and response)
-- **EMG startle**: -0.1 to 0.5 seconds (brief response)
-- **EDA SCR**: -1.0 to 10 seconds (1-3 s latency, slow recovery)
-
-### Event Labels and Conditions
+The default return is a dict containing `onset`, `duration`, and `label`; optional
+conditions use the singular key `condition`. Multi-channel input can add
+`events_channel` and generates conditions from the digital combination.
-Organize events by type and experimental conditions:
+Do not infer trigger semantics from amplitude alone. Verify polarity, threshold,
+debouncing, pulse width, dropped triggers, device latency, and whether simultaneous
+digital inputs are encoded as expected.
-```python
-# Example: Emotional picture experiment
-event_times = [1000, 2500, 4200, 5800] # Event onsets in samples
-event_labels = ['trial1', 'trial2', 'trial3', 'trial4']
-event_conditions = ['positive', 'negative', 'positive', 'neutral']
-
-epochs = nk.epochs_create(signals, events=event_times, sampling_rate=1000,
- epochs_start=-1, epochs_end=5,
- event_labels=event_labels,
- event_conditions=event_conditions)
-```
+## Build events explicitly when possible
-**Access epochs:**
```python
-# Epoch by number
-epoch_1 = epochs['1']
-
-# Filter by condition
-positive_epochs = {k: v for k, v in epochs.items() if v['Condition'][0] == 'positive'}
+events = nk.events_create(
+ event_onsets=[1000, 2500, 4000],
+ event_durations=[100, 100, 100],
+ event_labels=["1", "2", "3"],
+ event_conditions=["A", "B", "A"],
+)
```
-### Baseline Correction
+Labels must be unique. Keep experimental trial IDs outside participant-identifying
+names.
-Remove pre-stimulus baseline from epochs to isolate event-related changes:
-
-**Automatic (during epoch creation):**
-```python
-epochs = nk.epochs_create(data, events, sampling_rate=1000,
- epochs_start=-0.5, epochs_end=2.0,
- baseline_correction=True) # Subtracts mean of entire baseline
-```
+## `epochs_create()` semantics in 0.2.13
-**Manual (after epoch creation):**
-```python
-# Subtract baseline period mean
-baseline_start = -0.5 # seconds
-baseline_end = 0.0 # seconds
-
-for key, epoch in epochs.items():
- baseline_mask = (epoch.index >= baseline_start) & (epoch.index < baseline_end)
- baseline_mean = epoch[baseline_mask].mean()
- epochs[key] = epoch - baseline_mean
+```text
+epochs_create(
+ data, events=None, sampling_rate=1000,
+ epochs_start=0, epochs_end="from_events",
+ event_labels=None, event_conditions=None,
+ baseline_correction=False
+)
```
-**When to baseline correct:**
-- **ERPs**: Always (isolates event-related change)
-- **Cardiac/EDA**: Usually (removes inter-individual baseline differences)
-- **Absolute measures**: Sometimes not desired (e.g., analyzing absolute amplitude)
-
-## Epoch Analysis and Visualization
-
-### epochs_plot()
-
-Visualize individual or averaged epochs.
+- `epochs_start` and `epochs_end` are seconds relative to each event.
+- The data slice is `[start_sample, end_sample)` (end-exclusive).
+- Each epoch is a DataFrame in a dict keyed by label.
+- The original sample coordinate is stored in `Index`.
+- The DataFrame index is rebuilt with `numpy.linspace(..., endpoint=True)`, so the
+ displayed last index equals `epochs_end` even though the end sample is excluded.
+- `Label` and optional `Condition` are added as columns.
+- Events near a boundary are padded by internal buffers. Floating columns receive
+ NaN; integer columns can receive zero because of dtype preservation.
-```python
-nk.epochs_plot(epochs, column='ECG_Rate', condition=None, show=True)
-```
-
-**Parameters:**
-- `column`: Which signal column to plot
-- `condition`: Plot only specific condition (optional)
+The pinned probe for one signal, `-0.2` to `0.5` s at 100 Hz, produced 70 rows with
+an index from exactly `-0.2` through `0.5`. Do not derive sample count from that
+floating index. Use `Index`, the known sampling rate, and explicit half-open bounds.
-**Displays:**
-- Individual epoch traces (semi-transparent)
-- Average across epochs (bold line)
-- Optional: Shaded error (SEM or SD)
+## Boundary policy
-**Use cases:**
-- Visualize event-related responses
-- Compare conditions
-- Identify outlier epochs
+Decide before analysis:
-### epochs_average()
+- `drop`: remove incomplete trials and report condition-wise counts;
+- `pad`: retain them with an explicit validity mask; or
+- `error`: stop and repair event/window definitions.
-Compute grand average across epochs with statistics.
+Do not let NaN padding or integer zero padding silently become a physiological
+baseline. The dependency-free planner reports affected trials:
-```python
-average_epochs = nk.epochs_average(epochs, output='dict')
+```bash
+python skills/neurokit2/scripts/plan_epochs.py \
+ --events 1000,2500,4000 --event-unit samples \
+ --sampling-rate 100 --recording-samples 5000 \
+ --epoch-start -0.2 --epoch-end 0.8 \
+ --baseline-start -0.2 --baseline-end 0
```
-**Parameters:**
-- `output`: `'dict'` (default) or `'df'` (DataFrame)
-
-**Returns:**
-- Dictionary or DataFrame with:
- - `'Mean'`: Average across epochs at each time point
- - `'SD'`: Standard deviation
- - `'SE'`: Standard error of mean
- - `'CI_lower'`, `'CI_upper'`: 95% confidence intervals
+For events supplied in seconds, use `--event-unit seconds`; the planner rejects
+onsets/windows that do not map exactly to samples.
-**Use case:**
-- Compute event-related potentials (ERPs)
-- Grand average cardiac/EDA/EMG responses
-- Group-level analysis
+## Baseline correction
-**Condition-specific averaging:**
-```python
-# Separate averages by condition
-positive_epochs = {k: v for k, v in epochs.items() if v['Condition'][0] == 'positive'}
-negative_epochs = {k: v for k, v in epochs.items() if v['Condition'][0] == 'negative'}
-
-avg_positive = nk.epochs_average(positive_epochs)
-avg_negative = nk.epochs_average(negative_epochs)
-```
+`baseline_correction=True` subtracts the mean from epoch start through `t=0`
+(inclusive in the rebuilt time index). If the epoch starts after zero, it uses the
+epoch start. The operation is applied broadly to numeric columns present at that
+point, including marker/index columns.
-### epochs_to_df()
-
-Convert epochs dictionary to unified DataFrame.
+Prefer selective, manual correction:
```python
-epochs_df = nk.epochs_to_df(epochs)
-```
+epochs = nk.epochs_create(
+ processed,
+ events,
+ sampling_rate=100,
+ epochs_start=-0.2,
+ epochs_end=0.8,
+ baseline_correction=False,
+)
-**Returns:**
-- Single DataFrame with all epochs stacked
-- Includes `'Epoch'`, `'Time'`, `'Label'`, `'Condition'` columns
-- Facilitates statistical analysis and plotting with pandas/seaborn
-
-**Use case:**
-- Prepare data for mixed-effects models
-- Plotting with seaborn/plotly
-- Export to R or statistical software
-
-### epochs_to_array()
-
-Convert epochs to 3D NumPy array.
-
-```python
-epochs_array = nk.epochs_to_array(epochs, column='ECG_Rate')
+amplitude_columns = ["EDA_Phasic"]
+for epoch in epochs.values():
+ baseline = epoch.loc[(epoch.index >= -0.2) & (epoch.index < 0), amplitude_columns]
+ epoch.loc[:, amplitude_columns] = (
+ epoch.loc[:, amplitude_columns] - baseline.mean()
+ )
```
-**Returns:**
-- 3D array: (n_epochs, n_timepoints, n_columns)
+Prespecify baseline interval and estimand. Baseline subtraction is not universally
+appropriate for rates, binary peaks, phase, quality, or absolute tonic levels.
+Reject/flag a trial if its baseline has missing data or artifact rather than quietly
+using fewer samples.
-**Use case:**
-- Machine learning input (epoched features)
-- Custom array-based analysis
-- Statistical tests on array data
+## Conversions
-## Signal-Specific Event-Related Analysis
+`epochs_to_df()` stacks epochs and adds a `Time` column; the stable probe observed
+`Signal`, `Index`, `Label`, `Condition`, and `Time`.
-NeuroKit2 provides specialized event-related analysis for each signal type:
+`epochs_to_array()` does not take a `column` argument in 0.2.13. Equal-length,
+single-signal epochs produced shape `(time, epochs)` in the pinned probe. Multiple
+signal columns add an intermediate dimension. Unequal epochs are not supported.
-### ECG Event-Related
-```python
-ecg_epochs = nk.epochs_create(ecg_signals, events, sampling_rate=1000,
- epochs_start=-1, epochs_end=10)
-ecg_results = nk.ecg_eventrelated(ecg_epochs)
-```
-
-**Computed metrics:**
-- `ECG_Rate_Baseline`: Heart rate before event
-- `ECG_Rate_Min/Max`: Minimum/maximum rate during epoch
-- `ECG_Phase_*`: Cardiac phase at event onset
-- Rate dynamics across time windows
-
-### EDA Event-Related
-```python
-eda_epochs = nk.epochs_create(eda_signals, events, sampling_rate=100,
- epochs_start=-1, epochs_end=10)
-eda_results = nk.eda_eventrelated(eda_epochs)
-```
-
-**Computed metrics:**
-- `EDA_SCR`: Presence of SCR (binary)
-- `SCR_Amplitude`: Maximum SCR amplitude
-- `SCR_Latency`: Time to SCR onset
-- `SCR_RiseTime`, `SCR_RecoveryTime`
-- `EDA_Tonic`: Mean tonic level
+`epochs_average()` signature is:
-### RSP Event-Related
-```python
-rsp_epochs = nk.epochs_create(rsp_signals, events, sampling_rate=100,
- epochs_start=-0.5, epochs_end=5)
-rsp_results = nk.rsp_eventrelated(rsp_epochs)
+```text
+epochs_average(epochs, which=None, indices=["mean", "std", "ci"], show=False)
```
-**Computed metrics:**
-- `RSP_Rate_Mean`: Average breathing rate
-- `RSP_Amplitude_Mean`: Average breath depth
-- `RSP_Phase`: Respiratory phase at event
-- Rate/amplitude dynamics
-
-### EMG Event-Related
-```python
-emg_epochs = nk.epochs_create(emg_signals, events, sampling_rate=1000,
- epochs_start=-0.1, epochs_end=1.0)
-emg_results = nk.emg_eventrelated(emg_epochs)
-```
+For `which="Signal"`, the pinned schema contained `Time`, `Signal_Mean`,
+`Signal_SD`, `Signal_CI_low`, and `Signal_CI_high` (plus a reset-index column).
+This is not a universal event-related feature schema.
-**Computed metrics:**
-- `EMG_Activation`: Presence of activation
-- `EMG_Amplitude_Mean/Max`: Amplitude statistics
-- `EMG_Onset_Latency`: Time to activation onset
-- `EMG_Bursts`: Number of activation bursts
+## Signal-specific analysis
-### EOG Event-Related
-```python
-eog_epochs = nk.epochs_create(eog_signals, events, sampling_rate=500,
- epochs_start=-0.5, epochs_end=2.0)
-eog_results = nk.eog_eventrelated(eog_epochs)
-```
+Functions such as `ecg_eventrelated()`, `eda_eventrelated()`,
+`rsp_eventrelated()`, `ppg_eventrelated()`, `emg_eventrelated()`, and
+`eog_eventrelated()` inspect available processed columns. Their output changes when
+quality, phase, amplitude, condition, or trend columns are absent.
-**Computed metrics:**
-- `EOG_Blinks_N`: Number of blinks during epoch
-- `EOG_Rate_Mean`: Blink rate
-- Temporal blink distribution
+Use explicit dispatch:
-### PPG Event-Related
```python
-ppg_epochs = nk.epochs_create(ppg_signals, events, sampling_rate=100,
- epochs_start=-1, epochs_end=10)
-ppg_results = nk.ppg_eventrelated(ppg_epochs)
+ecg_features = nk.ecg_analyze(
+ epochs, sampling_rate=100, method="event-related"
+)
```
-**Computed metrics:**
-- Similar to ECG: rate dynamics, phase information
-
-## Practical Workflows
-
-### Complete Event-Related Analysis Pipeline
-
-```python
-import neurokit2 as nk
-
-# 1. Process physiological signals
-ecg_signals, ecg_info = nk.ecg_process(ecg, sampling_rate=1000)
-eda_signals, eda_info = nk.eda_process(eda, sampling_rate=100)
-
-# 2. Align sampling rates if needed
-eda_signals_resampled = nk.signal_resample(eda_signals, sampling_rate=100,
- desired_sampling_rate=1000)
-
-# 3. Merge signals into single DataFrame
-signals = pd.concat([ecg_signals, eda_signals_resampled], axis=1)
+`method="auto"` chooses event-related analysis when mean duration is under 10 seconds.
+That software threshold is not scientific justification for a window or analysis.
-# 4. Detect events
-events = nk.events_find(trigger_channel, threshold=0.5)
+## Trial QC and statistics
-# 5. Add event labels and conditions
-event_labels = ['trial1', 'trial2', 'trial3', ...]
-event_conditions = ['condition_A', 'condition_B', 'condition_A', ...]
+Before averaging:
-# 6. Create epochs
-epochs = nk.epochs_create(signals, events, sampling_rate=1000,
- epochs_start=-1.0, epochs_end=5.0,
- event_labels=event_labels,
- event_conditions=event_conditions,
- baseline_correction=True)
+1. inspect trigger detection against the raw marker channel;
+2. quantify boundary padding and missing baseline/post-event samples;
+3. apply modality-specific artifact rules without looking at condition outcomes;
+4. report retained trials per participant and condition;
+5. avoid threshold tuning on the same effects being tested; and
+6. model participant/trial hierarchy rather than treating epochs as independent.
-# 7. Signal-specific event-related analysis
-ecg_results = nk.ecg_eventrelated(epochs)
-eda_results = nk.eda_eventrelated(epochs)
+There is no universal minimum number of trials or universal epoch window. Determine
+both from the expected response, acquisition, study design, reliability, and power
+analysis.
-# 8. Merge results
-results = pd.merge(ecg_results, eda_results, left_index=True, right_index=True)
-
-# 9. Statistical analysis by condition
-results['Condition'] = event_conditions
-condition_comparison = results.groupby('Condition').mean()
-```
-
-### Handling Multiple Event Types
-
-```python
-# Different event types with different markers
-event_type1 = nk.events_find(trigger_ch1, threshold=0.5)
-event_type2 = nk.events_find(trigger_ch2, threshold=0.5)
-
-# Combine events with labels
-all_events = np.concatenate([event_type1['onset'], event_type2['onset']])
-event_labels = ['type1'] * len(event_type1['onset']) + ['type2'] * len(event_type2['onset'])
-
-# Sort by time
-sort_idx = np.argsort(all_events)
-all_events = all_events[sort_idx]
-event_labels = [event_labels[i] for i in sort_idx]
-
-# Create epochs
-epochs = nk.epochs_create(signals, all_events, sampling_rate=1000,
- epochs_start=-0.5, epochs_end=3.0,
- event_labels=event_labels)
-
-# Separate by type
-type1_epochs = {k: v for k, v in epochs.items() if v['Label'][0] == 'type1'}
-type2_epochs = {k: v for k, v in epochs.items() if v['Label'][0] == 'type2'}
-```
-
-### Quality Control and Artifact Rejection
-
-```python
-# Remove epochs with excessive noise or artifacts
-clean_epochs = {}
-for key, epoch in epochs.items():
- # Example: reject if EDA amplitude too high (movement artifact)
- if epoch['EDA_Phasic'].abs().max() < 5.0: # Threshold
- # Example: reject if heart rate change too large (invalid)
- if epoch['ECG_Rate'].max() - epoch['ECG_Rate'].min() < 50:
- clean_epochs[key] = epoch
-
-print(f"Kept {len(clean_epochs)}/{len(epochs)} epochs")
-
-# Analyze clean epochs
-results = nk.ecg_eventrelated(clean_epochs)
-```
+## Sources checked 2026-07-23
-## Statistical Considerations
-
-### Sample Size
-- **ERP/averaging**: 20-30+ trials per condition minimum
-- **Individual trial analysis**: Mixed-effects models handle variable trial counts
-- **Group comparisons**: Pilot data for power analysis
-
-### Time Window Selection
-- **A priori hypotheses**: Pre-register time windows based on literature
-- **Exploratory**: Use full epoch, correct for multiple comparisons
-- **Avoid**: Selecting windows based on observed data (circular)
-
-### Baseline Period
-- Should be free of anticipatory effects
-- Sufficient duration for stable estimate (500-1000 ms typical)
-- Shorter for fast dynamics (e.g., startle: 100 ms sufficient)
-
-### Condition Comparison
-- Repeated measures ANOVA for within-subject designs
-- Mixed-effects models for unbalanced data
-- Permutation tests for non-parametric comparisons
-- Correct for multiple comparisons (time points/signals)
-
-## Common Applications
-
-**Cognitive psychology:**
-- P300 ERP analysis
-- Error-related negativity (ERN)
-- Attentional blink
-- Working memory load effects
-
-**Affective neuroscience:**
-- Emotional picture viewing (EDA, HR, facial EMG)
-- Fear conditioning (HR deceleration, SCR)
-- Valence/arousal dimensions
-
-**Clinical research:**
-- Startle response (orbicularis oculi EMG)
-- Orienting response (HR deceleration)
-- Anticipation and prediction error
-
-**Psychophysiology:**
-- Cardiac defense response
-- Orienting vs. defensive reflexes
-- Respiratory changes during emotion
-
-**Human-computer interaction:**
-- User engagement during events
-- Surprise/violation of expectation
-- Cognitive load during task events
-
-## References
-
-- Luck, S. J. (2014). An introduction to the event-related potential technique (2nd ed.). MIT press.
-- Bradley, M. M., & Lang, P. J. (2000). Measuring emotion: Behavior, feeling, and physiology. In R. D. Lane & L. Nadel (Eds.), Cognitive neuroscience of emotion (pp. 242-276). Oxford University Press.
-- Boucsein, W. (2012). Electrodermal activity (2nd ed.). Springer.
-- Gratton, G., Coles, M. G., & Donchin, E. (1983). A new method for off-line removal of ocular artifact. Electroencephalography and clinical neurophysiology, 55(4), 468-484.
+- [Official Events API](https://neuropsychology.github.io/NeuroKit/functions/events.html)
+- [Official Epochs API](https://neuropsychology.github.io/NeuroKit/functions/epochs.html)
+- [Official event-related example](https://neuropsychology.github.io/NeuroKit/examples/bio_eventrelated/bio_eventrelated.html)
+- [Stable v0.2.13 epoch source](https://github.com/neuropsychology/NeuroKit/blob/v0.2.13/neurokit2/epochs/epochs_create.py)
+- [SPR EEG/ERP guideline index](https://sprweb.org/guidelines-papers)
diff --git a/skills/neurokit2/references/hrv.md b/skills/neurokit2/references/hrv.md
index e966461d..9d7280ac 100644
--- a/skills/neurokit2/references/hrv.md
+++ b/skills/neurokit2/references/hrv.md
@@ -1,480 +1,205 @@
-# Heart Rate Variability (HRV) Analysis
+# Heart-rate variability and RSA
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official HRV API/tutorial, and HRV/RSA measurement guidance.
-Heart Rate Variability (HRV) reflects the variation in time intervals between consecutive heartbeats, providing insights into autonomic nervous system regulation, cardiovascular health, and psychological state. NeuroKit2 provides comprehensive HRV analysis across time, frequency, and nonlinear domains.
+## Define the interval series
-## Main Function
+HRV analysis needs beat timing plus a defensible classification/correction policy.
+Distinguish:
-### hrv()
+- **RR/RRI**: intervals between detected R peaks;
+- **NN**: intervals between beats judged normal sinus beats; and
+- **PP/PRV**: intervals between peripheral pulse peaks.
-Compute all available HRV indices at once across all domains.
+Do not relabel automatically corrected RR or PPG intervals as NN. Preserve raw waveform,
+raw peaks, corrected peaks, excluded segments, correction categories, and interval units.
-```python
-hrv_indices = nk.hrv(peaks, sampling_rate=1000, show=False)
-```
-
-**Input:**
-- `peaks`: Dictionary with `'ECG_R_Peaks'` key or array of R-peak indices
-- `sampling_rate`: Signal sampling rate in Hz
-
-**Returns:**
-- DataFrame with HRV indices from all domains:
- - Time domain metrics
- - Frequency domain power spectra
- - Nonlinear complexity measures
-
-**This is a convenience wrapper** that combines:
-- `hrv_time()`
-- `hrv_frequency()`
-- `hrv_nonlinear()`
-
-## Time Domain Analysis
+Accepted NeuroKit2 inputs include:
-### hrv_time()
+- a list/array of peak sample indices;
+- marker/info objects from `ecg_peaks()`, `ppg_peaks()`, `ecg_process()`, or
+ `bio_process()`; and
+- a dict with `RRI` (milliseconds) and `RRI_Time` (seconds).
-Compute time-domain HRV metrics based on inter-beat intervals (IBIs).
+Always pass the sampling rate of the continuous signal in which peak indices were
+defined.
-```python
-hrv_time = nk.hrv_time(peaks, sampling_rate=1000)
-```
-
-### Key Metrics
-
-**Basic interval statistics:**
-- `HRV_MeanNN`: Mean of NN intervals (ms)
-- `HRV_SDNN`: Standard deviation of NN intervals (ms)
- - Reflects total HRV, captures all cyclic components
- - Requires ≥5 min for short-term, ≥24 hr for long-term
-- `HRV_RMSSD`: Root mean square of successive differences (ms)
- - High-frequency variability, reflects parasympathetic activity
- - More stable with shorter recordings
-
-**Successive difference measures:**
-- `HRV_SDSD`: Standard deviation of successive differences (ms)
- - Similar to RMSSD, correlated with parasympathetic activity
-- `HRV_pNN50`: Percentage of successive NN intervals differing >50ms
- - Parasympathetic indicator, may be insensitive in some populations
-- `HRV_pNN20`: Percentage of successive NN intervals differing >20ms
- - More sensitive alternative to pNN50
-
-**Range measures:**
-- `HRV_MinNN`, `HRV_MaxNN`: Minimum and maximum NN intervals (ms)
-- `HRV_CVNN`: Coefficient of variation (SDNN/MeanNN)
- - Normalized measure, useful for cross-subject comparison
-- `HRV_CVSD`: Coefficient of variation of successive differences (RMSSD/MeanNN)
-
-**Median-based statistics:**
-- `HRV_MedianNN`: Median NN interval (ms)
- - Robust to outliers
-- `HRV_MadNN`: Median absolute deviation of NN intervals
- - Robust dispersion measure
-- `HRV_MCVNN`: Median-based coefficient of variation
-
-**Advanced time-domain:**
-- `HRV_IQRNN`: Interquartile range of NN intervals
-- `HRV_pNN10`, `HRV_pNN25`, `HRV_pNN40`: Additional percentile thresholds
-- `HRV_TINN`: Triangular interpolation of NN interval histogram
-- `HRV_HTI`: HRV triangular index (total NN intervals / histogram height)
-
-### Recording Duration Requirements
-- **Ultra-short (< 5 min)**: RMSSD, pNN50 most reliable
-- **Short-term (5 min)**: Standard for clinical use, all time-domain valid
-- **Long-term (24 hr)**: Required for SDNN interpretation, captures circadian rhythms
-
-## Frequency Domain Analysis
-
-### hrv_frequency()
-
-Analyze HRV power across frequency bands using spectral analysis.
+## Current functions and schemas
```python
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000, ulf=(0, 0.0033), vlf=(0.0033, 0.04),
- lf=(0.04, 0.15), hf=(0.15, 0.4), vhf=(0.4, 0.5),
- psd_method='welch', normalize=True)
+time = nk.hrv_time(peaks, sampling_rate=250)
+frequency = nk.hrv_frequency(peaks, sampling_rate=250)
+nonlinear = nk.hrv_nonlinear(peaks, sampling_rate=250)
+all_domains = nk.hrv(peaks, sampling_rate=250)
```
-### Frequency Bands
-
-**Ultra-Low Frequency (ULF): 0-0.0033 Hz**
-- Requires ≥24 hour recording
-- Circadian rhythms, thermoregulation
-- Slow metabolic processes
-
-**Very-Low Frequency (VLF): 0.0033-0.04 Hz**
-- Requires ≥5 minute recording
-- Thermoregulation, hormonal fluctuations
-- Renin-angiotensin system, peripheral vasomotor activity
-
-**Low Frequency (LF): 0.04-0.15 Hz**
-- Mixed sympathetic and parasympathetic influences
-- Baroreceptor reflex activity
-- Blood pressure regulation (10-second rhythm)
+All four return one-row DataFrames. `hrv()` concatenates the available domains and can
+append RSA when its input contains processed respiration data. Columns vary with data
+length, kwargs, available modalities, and release.
-**High Frequency (HF): 0.15-0.4 Hz**
-- Parasympathetic (vagal) activity
-- Respiratory sinus arrhythmia
-- Synchronized with breathing (respiratory rate range)
+Pinned 0.2.13 observations:
-**Very-High Frequency (VHF): 0.4-0.5 Hz**
-- Rarely used, may reflect measurement noise
-- Requires careful interpretation
+- `hrv_time()` returned 25 columns, including `HRV_MeanNN`, `HRV_SDNN`,
+ `HRV_RMSSD`, `HRV_SDSD`, `HRV_CVNN`, `HRV_CVSD`, robust interval summaries,
+ `HRV_pNN50`, `HRV_pNN20`, `HRV_HTI`, and `HRV_TINN`. Long-segment indices
+ (`SDANN*`, `SDNNI*`) can be NaN when duration is insufficient.
+- `hrv_frequency()` returned exactly `HRV_ULF`, `HRV_VLF`, `HRV_LF`, `HRV_HF`,
+ `HRV_VHF`, `HRV_TP`, `HRV_LFHF`, `HRV_LFn`, `HRV_HFn`, and `HRV_LnHF` in the
+ default probe.
+- `hrv_nonlinear()` returned Poincaré, asymmetry, fragmentation, DFA/MFDFA,
+ entropy/fractal, Lempel–Ziv, and symbolic-dynamics columns. Stable 0.2.13 added
+ default `HRV_Symbolic_EqualProb4_*` features.
-### Key Metrics
+Do not hard-code a “complete” HRV column list. Persist `list(result.columns)` and map
+only prespecified outputs.
-**Absolute power (ms²):**
-- `HRV_ULF`, `HRV_VLF`, `HRV_LF`, `HRV_HF`, `HRV_VHF`: Power in each band
-- `HRV_TP`: Total power (variance of NN intervals)
-- `HRV_LFHF`: LF/HF ratio (sympathovagal balance)
+## Units and interval helpers
-**Normalized power:**
-- `HRV_LFn`: LF power / (LF + HF) - normalized LF
-- `HRV_HFn`: HF power / (LF + HF) - normalized HF
-- `HRV_LnHF`: Natural logarithm of HF (log-normal distribution)
+Time-domain metrics are milliseconds where applicable. Frequency power is based on
+millisecond intervals and therefore commonly has ms²-derived units, but normalization
+and estimator settings change interpretation.
-**Peak frequencies:**
-- `HRV_LFpeak`, `HRV_HFpeak`: Frequency of maximum power in each band
-- Useful for identifying dominant oscillations
-
-### Power Spectral Density Methods
-
-**Welch's method (default):**
```python
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000, psd_method='welch')
+processed_rri, processed_time, interpolation_rate = nk.intervals_process(
+ rri_ms,
+ intervals_time=time_s,
+ interpolate=True,
+ interpolation_rate=4,
+ detrend=None,
+)
+peaks = nk.intervals_to_peaks(rri_ms, sampling_rate=1000)
```
-- Windowed FFT with overlap
-- Smoother spectra, reduced variance
-- Good for standard HRV analysis
-**Lomb-Scargle periodogram:**
-```python
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000, psd_method='lomb')
+`intervals_process()` returns three objects: intervals in milliseconds, timestamps in
+seconds, and interpolation rate. `intervals_to_peaks()` returns integer peak indices,
+with a constructed first peak. Verify external-device interval definitions and dropped
+beats before conversion.
+
+## Recording duration
+
+Duration requirements are metric-, population-, protocol-, and estimator-specific.
+Use these conservative planning principles:
+
+- Five minutes is the conventional standardized short-term HRV window.
+- RMSSD can be computed on shorter windows, but ultra-short estimates require
+ endpoint- and population-specific reliability/validity evidence.
+- A spectral segment should contain enough cycles of the lowest frequency interpreted.
+ Five minutes is a practical reference for conventional LF/HF short-term analysis.
+- Do not interpret ULF from a short recording; it is conventionally associated with
+ long, often 24-hour recordings.
+- VLF physiological interpretation in short recordings is uncertain.
+- Entropy, DFA, MFDFA, correlation dimension, and RQA need enough beats for stable
+ estimation; defaults returning a number do not establish adequacy.
+
+Do not compare metrics estimated from unequal durations without a validated strategy.
+Report exact usable duration and beat count after exclusions, not nominal acquisition
+duration.
+
+## Ectopy and artifact policy
+
+1. Inspect ECG/PPG quality and peak overlays.
+2. Review the tachogram and interval histogram.
+3. Identify non-sinus beats separately from detector errors when possible.
+4. Report raw and corrected beat counts and percentage.
+5. Limit interpolation/correction according to a prespecified exclusion rule.
+6. Repeat key analyses under plausible correction choices.
+
+`ecg_process()` requests artifact correction automatically in 0.2.13. If that is not
+the planned policy, run `ecg_clean()` and `ecg_peaks()` explicitly.
+
+Heavy correction can manufacture smooth HRV. A segment with excessive ectopy,
+detachment, or motion may need exclusion rather than interpolation.
+
+## Frequency domain
+
+Stable signature:
+
+```text
+hrv_frequency(
+ peaks, sampling_rate=1000,
+ ulf=(0, 0.0033), vlf=(0.0033, 0.04),
+ lf=(0.04, 0.15), hf=(0.15, 0.4), vhf=(0.4, 0.5),
+ psd_method="welch", normalize=True, interpolation_rate=100, ...
+)
```
-- Handles unevenly sampled data
-- No interpolation required
-- Better for noisy or artifact-containing data
-**Multitaper method:**
-```python
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000, psd_method='multitapers')
-```
-- Superior spectral estimation
-- Reduced variance with minimal bias
-- Computationally intensive
+Set `interpolation_rate=4` to approximate a common Kubios interpolation choice; set it
+to `None` for already-interpolated intervals or Lomb–Scargle. Record detrending,
+interpolation, PSD method, window/order, frequency bands, and normalization.
-**Burg autoregressive:**
-```python
-hrv_freq = nk.hrv_frequency(peaks, sampling_rate=1000, psd_method='burg', order=16)
-```
-- Parametric method
-- Smooth spectra with well-defined peaks
-- Requires order selection
-
-### Interpretation Guidelines
-
-**LF/HF Ratio:**
-- Traditionally interpreted as sympathovagal balance
-- **Caution**: Recent evidence questions this interpretation
-- LF reflects both sympathetic and parasympathetic influences
-- Context-dependent: controlled respiration affects HF
+Do **not** interpret `HRV_LFHF` as a direct “sympathovagal balance.” LF contains mixed
+influences; HF depends on breathing frequency/depth and can miss respiratory variation
+outside the default 0.15–0.4 Hz band.
-**HF Power:**
-- Reliable parasympathetic indicator
-- Increases with: rest, relaxation, deep breathing
-- Decreases with: stress, anxiety, sympathetic activation
+## PPG-derived variability
-**Recording Requirements:**
-- **Minimum**: 60 seconds for LF/HF estimation
-- **Recommended**: 2-5 minutes for short-term HRV
-- **Optimal**: 5 minutes per Task Force standards
-- **Long-term**: 24 hours for ULF analysis
+PPG pulse timing includes pre-ejection and pulse-transit effects, and varies with site,
+vascular state, posture, temperature, motion, contact pressure, and sensor design.
+Label results PRV/PPG-derived HRV and validate against synchronized ECG for the endpoint,
+conditions, sites, and population. Agreement at rest does not imply agreement during
+exercise or stress.
-## Nonlinear Domain Analysis
+## Respiratory sinus arrhythmia
-### hrv_nonlinear()
+Stable signature:
-Compute complexity, entropy, and fractal measures reflecting autonomic dynamics.
-
-```python
-hrv_nonlinear = nk.hrv_nonlinear(peaks, sampling_rate=1000)
+```text
+hrv_rsa(
+ ecg_signals, rsp_signals=None, rpeaks=None,
+ sampling_rate=1000, continuous=False,
+ window=None, window_number=None
+)
```
-### Poincaré Plot Indices
-
-**Poincaré plot**: NN(i+1) vs NN(i) scatter plot geometry
-
-- `HRV_SD1`: Standard deviation perpendicular to line of identity (ms)
- - Short-term HRV, fast beat-to-beat variability
- - Reflects parasympathetic activity
- - Mathematically related to RMSSD: SD1 ≈ RMSSD/√2
-
-- `HRV_SD2`: Standard deviation along line of identity (ms)
- - Long-term HRV, slow variability
- - Reflects sympathetic and parasympathetic activity
- - Related to SDNN
-
-- `HRV_SD1SD2`: Ratio SD1/SD2
- - Balance between short and long-term variability
- - <1: predominantly long-term variability
-
-- `HRV_SD2SD1`: Ratio SD2/SD1
- - Inverse of SD1SD2
-
-- `HRV_S`: Area of ellipse (π × SD1 × SD2)
- - Total HRV magnitude
-
-- `HRV_CSI`: Cardiac Sympathetic Index (SD2/SD1)
- - Proposed sympathetic indicator
-
-- `HRV_CVI`: Cardiac Vagal Index (log10(SD1 × SD2))
- - Proposed parasympathetic indicator
-
-- `HRV_CSI_Modified`: Modified CSI (SD2²/(SD1 × SD2))
-
-### Heart Rate Asymmetry
-
-Analyzes whether heart rate accelerations and decelerations contribute differently to HRV.
-
-- `HRV_GI`: Guzik's Index - asymmetry of short-term variability
-- `HRV_SI`: Slope Index - asymmetry of long-term variability
-- `HRV_AI`: Area Index - overall asymmetry
-- `HRV_PI`: Porta's Index - percentage of decelerations
-- `HRV_C1d`, `HRV_C2d`: Deceleration contributions
-- `HRV_C1a`, `HRV_C2a`: Acceleration contributions
-- `HRV_SD1d`, `HRV_SD1a`: Poincaré SD1 for decelerations/accelerations
-- `HRV_SD2d`, `HRV_SD2a`: Poincaré SD2 for decelerations/accelerations
-
-**Interpretation:**
-- Healthy individuals: asymmetry present (more/larger decelerations)
-- Clinical populations: reduced asymmetry
-- Reflects differential autonomic control of acceleration vs. deceleration
-
-### Entropy Measures
-
-**Approximate Entropy (ApEn):**
-- `HRV_ApEn`: Regularity measure, lower = more regular/predictable
-- Sensitive to data length, order m, tolerance r
-
-**Sample Entropy (SampEn):**
-- `HRV_SampEn`: Improved ApEn, less dependent on data length
-- More consistent with short recordings
-- Lower values = more regular patterns
-
-**Multiscale Entropy (MSE):**
-- `HRV_MSE`: Complexity across multiple time scales
-- Distinguishes true complexity from randomness
-
-**Fuzzy Entropy:**
-- `HRV_FuzzyEn`: Fuzzy membership functions for pattern matching
-- More stable with short data
-
-**Shannon Entropy:**
-- `HRV_ShanEn`: Information-theoretic randomness measure
-
-### Fractal Measures
-
-**Detrended Fluctuation Analysis (DFA):**
-- `HRV_DFA_alpha1`: Short-term fractal scaling exponent (4-11 beats)
- - α1 > 1: correlations, reduced in heart disease
- - α1 ≈ 1: pink noise, healthy
- - α1 < 0.5: anti-correlations
-
-- `HRV_DFA_alpha2`: Long-term fractal scaling exponent (>11 beats)
- - Reflects long-range correlations
-
-- `HRV_DFA_alpha1alpha2`: Ratio α1/α2
-
-**Correlation Dimension:**
-- `HRV_CorDim`: Dimensionality of attractor in phase space
-- Indicates system complexity
-
-**Higuchi Fractal Dimension:**
-- `HRV_HFD`: Complexity and self-similarity
-- Higher values = more complex, irregular
-
-**Petrosian Fractal Dimension:**
-- `HRV_PFD`: Alternative complexity measure
-- Computationally efficient
-
-**Katz Fractal Dimension:**
-- `HRV_KFD`: Waveform complexity
-
-### Heart Rate Fragmentation
-
-Quantifies abnormal short-term fluctuations reflecting autonomic dysregulation.
-
-- `HRV_PIP`: Percentage of inflection points
- - Normal: ~50%, Fragmented: >70%
-- `HRV_IALS`: Inverse average length of acceleration/deceleration segments
-- `HRV_PSS`: Percentage of short segments (<3 beats)
-- `HRV_PAS`: Percentage of NN intervals in alternation segments
-
-**Clinical relevance:**
-- Increased fragmentation associated with cardiovascular risk
-- Independent predictor beyond traditional HRV metrics
-
-### Other Nonlinear Metrics
-
-- `HRV_Hurst`: Hurst exponent (long-range dependence)
-- `HRV_LZC`: Lempel-Ziv complexity (algorithmic complexity)
-- `HRV_MFDFA`: Multifractal DFA indices
-
-## Specialized HRV Functions
-
-### hrv_rsa()
-
-Respiratory Sinus Arrhythmia - heart rate modulation by breathing.
+Use synchronized processed ECG and respiration DataFrames:
```python
-rsa = nk.hrv_rsa(peaks, rsp_signal, sampling_rate=1000, method='porges1980')
-```
-
-**Methods:**
-- `'porges1980'`: Porges-Bohrer method (band-pass filtered HR around breathing frequency)
-- `'harrison2021'`: Peak-to-trough RSA (max-min HR per breath cycle)
-
-**Requirements:**
-- Both ECG and respiratory signals
-- Synchronized timing
-- At least several breath cycles
-
-**Returns:**
-- `RSA`: RSA magnitude (beats/min or similar units depending on method)
-
-### hrv_rqa()
-
-Recurrence Quantification Analysis - nonlinear dynamics from phase space reconstruction.
-
-```python
-rqa = nk.hrv_rqa(peaks, sampling_rate=1000)
-```
-
-**Metrics:**
-- `RQA_RR`: Recurrence rate - system predictability
-- `RQA_DET`: Determinism - percentage of recurrent points forming lines
-- `RQA_LMean`, `RQA_LMax`: Average and maximum diagonal line length
-- `RQA_ENTR`: Shannon entropy of line lengths - complexity
-- `RQA_LAM`: Laminarity - system trapped in specific states
-- `RQA_TT`: Trapping time - duration in laminar states
-
-**Use case:**
-- Detect transitions in physiological states
-- Assess system determinism vs. stochasticity
-
-## Interval Processing
-
-### intervals_process()
-
-Preprocess RR-intervals before HRV analysis.
-
-```python
-processed_intervals = nk.intervals_process(rr_intervals, interpolate=False,
- interpolate_sampling_rate=1000)
-```
-
-**Operations:**
-- Removes physiologically implausible intervals
-- Optional: interpolates to regular sampling
-- Optional: detrending to remove slow trends
-
-**Use case:**
-- When working with pre-extracted RR intervals
-- Cleaning intervals from external devices
-- Preparing data for frequency-domain analysis
-
-### intervals_to_peaks()
-
-Convert interval data (RR, NN) to peak indices for HRV analysis.
-
-```python
-peaks_dict = nk.intervals_to_peaks(rr_intervals, sampling_rate=1000)
-```
-
-**Use case:**
-- Import data from external HRV devices
-- Work with interval data from commercial systems
-- Convert between interval and peak representations
-
-## Practical Considerations
-
-### Minimum Recording Duration
-
-| Analysis | Minimum Duration | Optimal Duration |
-|----------|-----------------|------------------|
-| RMSSD, pNN50 | 30 sec | 5 min |
-| SDNN | 5 min | 5 min (short), 24 hr (long) |
-| LF, HF power | 2 min | 5 min |
-| VLF power | 5 min | 10+ min |
-| ULF power | 24 hr | 24 hr |
-| Nonlinear (ApEn, SampEn) | 100-300 beats | 500+ beats |
-| DFA | 300 beats | 1000+ beats |
-
-### Artifact Management
-
-**Preprocessing:**
-```python
-# Detect R-peaks with artifact correction
-peaks, info = nk.ecg_peaks(cleaned_ecg, sampling_rate=1000, correct_artifacts=True)
-
-# Or manually process intervals
-processed = nk.intervals_process(rr_intervals, interpolate=False)
+rsa = nk.hrv_rsa(
+ ecg_signals,
+ rsp_signals,
+ rpeaks=ecg_info,
+ sampling_rate=100,
+ continuous=False,
+)
```
-**Quality checks:**
-- Visual inspection of tachogram (NN intervals over time)
-- Identify physiologically implausible intervals (<300 ms or >2000 ms)
-- Check for sudden jumps or missing beats
-- Assess signal quality before analysis
-
-### Standardization and Comparison
-
-**Task Force Standards (1996):**
-- 5-minute recordings for short-term
-- Supine, controlled breathing recommended
-- 24-hour for long-term assessment
-
-**Normalization:**
-- Consider age, sex, fitness level effects
-- Time of day and circadian effects
-- Body position (supine vs. standing)
-- Breathing rate and depth
-
-**Inter-individual variability:**
-- HRV has large between-subject variation
-- Within-subject changes more interpretable
-- Baseline comparisons preferred
-
-## Clinical and Research Applications
-
-**Cardiovascular health:**
-- Reduced HRV: risk factor for cardiac events
-- SDNN, DFA alpha1: prognostic indicators
-- Post-MI monitoring
-
-**Psychological state:**
-- Anxiety/stress: reduced HRV (especially RMSSD, HF)
-- Depression: altered autonomic balance
-- PTSD: fragmentation indices
-
-**Athletic performance:**
-- Training load monitoring via daily RMSSD
-- Overtraining: reduced HRV
-- Recovery assessment
-
-**Neuroscience:**
-- Emotion regulation studies
-- Cognitive load assessment
-- Brain-heart axis research
-
-**Aging:**
-- HRV decreases with age
-- Complexity measures decline
-- Baseline reference needed
-
-## References
-
-- Task Force of the European Society of Cardiology. (1996). Heart rate variability: standards of measurement, physiological interpretation and clinical use. Circulation, 93(5), 1043-1065.
-- Shaffer, F., & Ginsberg, J. P. (2017). An overview of heart rate variability metrics and norms. Frontiers in public health, 5, 258.
-- Peng, C. K., Havlin, S., Stanley, H. E., & Goldberger, A. L. (1995). Quantification of scaling exponents and crossover phenomena in nonstationary heartbeat time series. Chaos, 5(1), 82-87.
-- Guzik, P., Piskorski, J., Krauze, T., Wykretowicz, A., & Wysocki, H. (2006). Heart rate asymmetry by Poincaré plots of RR intervals. Biomedizinische Technik/Biomedical Engineering, 51(4), 272-275.
-- Costa, M., Goldberger, A. L., & Peng, C. K. (2005). Multiscale entropy analysis of biological signals. Physical review E, 71(2), 021906.
+The pinned summary returned a dict with P2T and Gates statistics, including
+`RSA_P2T_Mean`, `RSA_P2T_SD`, `RSA_P2T_NoRSA`, `RSA_PorgesBohrer`, and Gates
+mean/SD/log fields. `continuous=True` returned a same-length DataFrame with
+`RSA_P2T` and `RSA_Gates`.
+
+Requirements:
+
+- shared clock, sampling grid, and defined lag/drift policy;
+- valid R peaks and respiration cycles;
+- enough cycles/windows for the chosen method;
+- measured respiration rate and context; and
+- reporting of P2T/Gates method and all window parameters.
+
+RSA/HF-HRV is often related to cardiac vagal modulation but is not a direct,
+context-free vagal-tone assay. Respiration, activity, beta-adrenergic influence, age,
+posture, and within- versus between-person contrasts can change interpretation.
+
+## Analysis/report checklist
+
+- package version and observed output schema;
+- ECG/PPG source, sensor/site, sampling, clock, units, and raw-data access;
+- duration, usable duration, beat count, and exclusions;
+- peak detector, quality method, ectopy/artifact criteria, and correction percentage;
+- RRI/NN/PRV terminology;
+- PSD/interpolation/detrending/bands/normalization;
+- respiration measurement and rate/depth context;
+- prespecified metrics and multiplicity control; and
+- no diagnostic, monitoring, or medical-device claim without separate validation.
+
+## Sources checked 2026-07-23
+
+- [Official HRV API](https://neuropsychology.github.io/NeuroKit/functions/hrv.html)
+- [Official HRV example](https://neuropsychology.github.io/NeuroKit/examples/ecg_hrv/ecg_hrv.html)
+- [Pham et al. (2021), NeuroKit2 HRV review/tutorial](https://doi.org/10.3390/s21123998)
+- [Quigley et al. (2024), current SPR HR/HRV guidelines](https://doi.org/10.1111/psyp.14604)
+- [ESC/NASPE Task Force (1996)](https://pubmed.ncbi.nlm.nih.gov/8598068/)
+- [Berntson et al. (1997), interpretive caveats](https://doi.org/10.1111/j.1469-8986.1997.tb02140.x)
+- [Laborde et al. (2017), planning/reporting](https://doi.org/10.3389/fpsyg.2017.00213)
+- [Grossman & Taylor (2007), RSA caveats](https://doi.org/10.1016/j.biopsycho.2005.11.014)
diff --git a/skills/neurokit2/references/ppg.md b/skills/neurokit2/references/ppg.md
index 81d8d186..5de45dec 100644
--- a/skills/neurokit2/references/ppg.md
+++ b/skills/neurokit2/references/ppg.md
@@ -1,413 +1,191 @@
-# Photoplethysmography (PPG) Analysis
+# Photoplethysmography
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official PPG API, 0.2.13 release notes, and measurement guidance.
-Photoplethysmography (PPG) measures blood volume changes in microvascular tissue using optical sensors. PPG is widely used in wearable devices, pulse oximeters, and clinical monitors for heart rate, pulse characteristics, and cardiovascular assessment.
+## Acquisition contract
-## Main Processing Pipeline
+Record sensor mode (reflectance/transmission), wavelength(s), anatomical site,
+attachment/contact pressure, device/firmware, raw unit/range, ambient-light handling,
+sampling rate, clock, temperature/perfusion, activity/posture, and motion/accelerometer
+channels. Validate across representative skin pigmentation, anatomy, age, vascular
+state, motion, and intended population.
-### ppg_process()
+PPG is optical blood-volume-pulse measurement, not cardiac electrical activity.
+Pulse timing and morphology depend on site and vascular/transit dynamics.
-Automated PPG signal processing pipeline.
+## Stable high-level pipeline
```python
-signals, info = nk.ppg_process(ppg_signal, sampling_rate=100, method='elgendi')
+signals, info = nk.ppg_process(
+ ppg,
+ sampling_rate=100,
+ method="elgendi",
+ method_quality="templatematch",
+)
```
-**Pipeline steps:**
-1. Signal cleaning (filtering)
-2. Systolic peak detection
-3. Heart rate calculation
-4. Signal quality assessment
+Pinned 0.2.13 default columns:
-**Returns:**
-- `signals`: DataFrame with:
- - `PPG_Clean`: Filtered PPG signal
- - `PPG_Peaks`: Systolic peak markers
- - `PPG_Rate`: Instantaneous heart rate (BPM)
- - `PPG_Quality`: Signal quality indicator
-- `info`: Dictionary with peak indices and parameters
-
-**Methods:**
-- `'elgendi'`: Elgendi et al. (2013) algorithm (default, robust)
-- `'nabian2018'`: Nabian et al. (2018) approach
-
-## Preprocessing Functions
-
-### ppg_clean()
-
-Prepare raw PPG signal for peak detection.
-
-```python
-cleaned_ppg = nk.ppg_clean(ppg_signal, sampling_rate=100, method='elgendi')
-```
-
-**Methods:**
-
-**1. Elgendi (default):**
-- Butterworth bandpass filter (0.5-8 Hz)
-- Removes baseline drift and high-frequency noise
-- Optimized for peak detection reliability
-
-**2. Nabian2018:**
-- Alternative filtering approach
-- Different frequency characteristics
-
-**PPG signal characteristics:**
-- **Systolic peak**: Rapid upstroke, sharp peak (cardiac ejection)
-- **Dicrotic notch**: Secondary peak (aortic valve closure)
-- **Baseline**: Slow drift due to respiration, movement, perfusion
-
-### ppg_peaks()
-
-Detect systolic peaks in PPG signal.
-
-```python
-peaks, info = nk.ppg_peaks(cleaned_ppg, sampling_rate=100, method='elgendi',
- correct_artifacts=False)
-```
-
-**Methods:**
-- `'elgendi'`: Two moving averages with dynamic thresholding
-- `'bishop'`: Bishop's algorithm
-- `'nabian2018'`: Nabian's approach
-- `'scipy'`: Simple scipy peak detection
-
-**Artifact correction:**
-- Set `correct_artifacts=True` for physiological plausibility checks
-- Removes spurious peaks based on inter-beat interval outliers
-
-**Returns:**
-- Dictionary with `'PPG_Peaks'` key containing peak indices
-
-**Typical inter-beat intervals:**
-- Resting adult: 600-1200 ms (50-100 BPM)
-- Athlete: Can be longer (bradycardia)
-- Stressed/exercising: Shorter (<600 ms, >100 BPM)
-
-### ppg_findpeaks()
-
-Low-level peak detection with algorithm comparison.
-
-```python
-peaks_dict = nk.ppg_findpeaks(cleaned_ppg, sampling_rate=100, method='elgendi')
-```
-
-**Use case:**
-- Custom parameter tuning
-- Algorithm testing
-- Research method development
-
-## Analysis Functions
-
-### ppg_analyze()
-
-Automatically select event-related or interval-related analysis.
-
-```python
-analysis = nk.ppg_analyze(signals, sampling_rate=100)
+```text
+PPG_Raw, PPG_Clean, PPG_Rate, PPG_Quality, PPG_Peaks
```
-**Mode selection:**
-- Duration < 10 seconds → event-related
-- Duration ≥ 10 seconds → interval-related
+`info` contained `PPG_Peaks`, `sampling_rate`, and peak/correction method metadata.
+The live doc's older codebook can omit `PPG_Quality`; stable runtime/source includes it.
-### ppg_eventrelated()
+## Cleaning and peak methods
-Analyze PPG responses to discrete events/stimuli.
+For explicit selection:
```python
-results = nk.ppg_eventrelated(epochs)
+clean = nk.ppg_clean(
+ ppg,
+ sampling_rate=100,
+ method="elgendi",
+)
+markers, peak_info = nk.ppg_peaks(
+ clean,
+ sampling_rate=100,
+ method="elgendi",
+ correct_artifacts=False,
+)
```
-**Computed metrics (per epoch):**
-- `PPG_Rate_Baseline`: Heart rate before event
-- `PPG_Rate_Min/Max`: Minimum/maximum heart rate during epoch
-- Rate dynamics across epoch time windows
+Stable cleaning methods include:
-**Use cases:**
-- Cardiovascular responses to emotional stimuli
-- Cognitive load assessment
-- Stress reactivity paradigms
+- `elgendi`;
+- `nabian2018` (can use expected heart rate);
+- `langevin2021`;
+- `goda2024`; and
+- `none`.
-### ppg_intervalrelated()
+Stable peak methods include:
-Analyze extended PPG recordings.
+- `elgendi`;
+- `bishop` (peaks plus pulse onsets);
+- `charlton` (MSPTDfast v2; peaks plus onsets); and
+- `charlton2024` (superseded v1).
-```python
-results = nk.ppg_intervalrelated(signals, sampling_rate=100)
-```
+Method-dependent extra outputs are a primary reason not to hard-code one schema.
+Validate peak/onset performance against labeled data at the actual site, rate,
+perfusion, motion, and population.
-**Computed metrics:**
-- `PPG_Rate_Mean`: Average heart rate
-- Heart rate variability (HRV) metrics
- - Delegates to `hrv()` function
- - Time, frequency, and nonlinear domains
+`correct_artifacts=True` uses the cardiac peak-correction path. Retain raw/corrected
+peaks and correction categories; correction cannot repair a low-quality optical
+waveform.
-**Recording duration:**
-- Minimum: 60 seconds for basic rate
-- HRV analysis: 2-5 minutes recommended
-
-**Use cases:**
-- Resting state cardiovascular assessment
-- Wearable device data analysis
-- Long-term heart rate monitoring
-
-## Quality Assessment
-
-### ppg_quality()
-
-Assess signal quality and reliability.
+## Quality outputs added/expanded in 0.2.13
```python
-quality = nk.ppg_quality(ppg_signal, sampling_rate=100, method='averageQRS')
+quality = nk.ppg_quality(
+ clean,
+ peaks=peak_info["PPG_Peaks"],
+ sampling_rate=100,
+ method="templatematch",
+)
```
-**Methods:**
-
-**1. averageQRS (default):**
-- Template matching approach
-- Correlates each pulse with average template
-- Returns quality scores 0-1 per beat
-- Threshold: >0.6 = acceptable quality
-
-**2. dissimilarity:**
-- Topographic dissimilarity measures
-- Detects morphological changes
+Stable quality methods and scales differ:
-**Use cases:**
-- Identify corrupted segments
-- Filter low-quality data before analysis
-- Validate peak detection accuracy
+- `templatematch`: continuous similarity, typically 0–1;
+- `dissimilarity`: unbounded, where zero is highest similarity;
+- `ho2025`/interval-consistency path: binary interval quality;
+- `skewness`, `kurtosis`, `entropy`: unbounded windowed metrics;
+- `perfusion`: percentage-like 0–100 and requires raw PPG; and
+- `relative_power`: 0–1, requires raw PPG, and defaults to 60 s windows.
-**Common quality issues:**
-- Motion artifacts: abrupt signal changes
-- Poor sensor contact: low amplitude, noise
-- Vasoconstriction: reduced signal amplitude (cold, stress)
+No threshold is universal across these outputs. Name the method and direction/scale.
+Short signals can be invalid for a method's default window. `ppg_process()` passes
+peak indices—not the whole info dict—to quality estimation.
-## Utility Functions
+Quality relative to an average pulse does not prove physiological accuracy: repeated
+motion-corrupted beats can be morphologically consistent. Combine morphology, motion,
+contact/perfusion, missingness, detector agreement, and endpoint-specific validation.
-### ppg_segment()
+## Sampling and preprocessing
-Extract individual pulses for morphological analysis.
+Sampling requirements depend on endpoint:
-```python
-pulses = nk.ppg_segment(cleaned_ppg, peaks, sampling_rate=100)
-```
+- pulse rate needs less bandwidth than morphology, onset timing, or derivatives;
+- wrist wearables commonly use lower rates than laboratory finger systems;
+- resampling cannot recover missing onset precision or a dicrotic feature; and
+- a nominal rate does not establish clock accuracy or anti-alias filtering.
-**Returns:**
-- Dictionary of pulse epochs, each centered on systolic peak
-- Enables pulse-to-pulse comparison
-- Morphology analysis across conditions
+Do not prescribe one universal minimum. Validate rate and filters for the exact
+detector/feature and report native/processed rates. Process at native rate before
+multimodal alignment when possible.
-**Use cases:**
-- Pulse wave analysis
-- Arterial stiffness proxies
-- Vascular aging assessment
+Motion, contact pressure, ambient light, vasoconstriction, temperature, pigmentation,
+site, and clipping can all change amplitude/morphology. Preserve a quality/artifact
+mask and accelerometry where available. Avoid interpolating through corrupted pulses.
-### ppg_methods()
-
-Document preprocessing methods used in analysis.
+## PPG-derived variability is PRV
```python
-methods_info = nk.ppg_methods(method='elgendi')
+prv = nk.hrv_time(peak_info, sampling_rate=100)
```
-**Returns:**
-- String documenting the processing pipeline
-- Useful for methods sections in publications
-
-## Simulation and Visualization
+NeuroKit2 accepts PPG peaks in HRV functions, but interpretation remains pulse-rate
+variability. PRV contains pre-ejection and pulse-transit variability and can differ
+from ECG HRV by site, posture, respiration, activity, temperature, and vascular state.
-### ppg_simulate()
+For an HRV-equivalence claim:
-Generate synthetic PPG signals for testing.
-
-```python
-synthetic_ppg = nk.ppg_simulate(duration=60, sampling_rate=100, heart_rate=70,
- noise=0.1, random_state=42)
-```
+1. acquire synchronized ECG and PPG;
+2. validate pulse/beat matching and lag/drift;
+3. prespecify agreement metrics and acceptable error for each HRV endpoint;
+4. test rest, task/activity, motion, and relevant populations/sites; and
+5. report PRV terminology when equivalence is not established.
-**Parameters:**
-- `heart_rate`: Mean BPM (default: 70)
-- `heart_rate_std`: HRV magnitude
-- `noise`: Gaussian noise level
-- `random_state`: Reproducibility seed
+Do not infer ECG morphology, rhythm diagnosis, oxygen saturation, blood pressure, or
+arterial stiffness from this basic PPG pipeline.
-**Use cases:**
-- Algorithm validation
-- Parameter optimization
-- Educational demonstrations
-
-### ppg_plot()
-
-Visualize processed PPG signal.
+## Event and interval analysis
```python
-nk.ppg_plot(signals, info, static=True)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=100,
+ epochs_start=-1,
+ epochs_end=10,
+ baseline_correction=False,
+)
+event_features = nk.ppg_eventrelated(epochs)
+interval_features = nk.ppg_intervalrelated(signals)
```
-**Displays:**
-- Raw and cleaned PPG signal
-- Detected systolic peaks
-- Instantaneous heart rate trace
-- Signal quality indicators
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 20 Hz (basic heart rate)
-- **Standard**: 50-100 Hz (most wearables)
-- **High-resolution**: 200-500 Hz (research, pulse wave analysis)
-- **Excessive**: >1000 Hz (unnecessary for PPG)
-
-### Recording Duration
-- **Heart rate**: ≥10 seconds (few beats)
-- **HRV analysis**: 2-5 minutes minimum
-- **Long-term monitoring**: Hours to days (wearables)
-
-### Sensor Placement
-
-**Common sites:**
-- **Fingertip**: Highest signal quality, most common
-- **Earlobe**: Less motion artifact, clinical use
-- **Wrist**: Wearable devices (smartwatches)
-- **Forehead**: Reflectance mode, medical monitoring
-
-**Transmittance vs. Reflectance:**
-- **Transmittance**: Light passes through tissue (fingertip, earlobe)
- - Higher signal quality
- - Less motion artifact
-- **Reflectance**: Light reflected from tissue (wrist, forehead)
- - More susceptible to noise
- - Convenient for wearables
-
-### Common Issues and Solutions
-
-**Low signal amplitude:**
-- Poor perfusion: warm hands, increase blood flow
-- Sensor contact: adjust placement, clean skin
-- Vasoconstriction: environmental temperature, stress
-
-**Motion artifacts:**
-- Dominant issue in wearables
-- Adaptive filtering, accelerometer-based correction
-- Template matching, outlier rejection
-
-**Baseline drift:**
-- Respiratory modulation (normal)
-- Movement or pressure changes
-- High-pass filtering or detrending
-
-**Missing peaks:**
-- Low-quality signal: check sensor contact
-- Algorithm parameters: adjust threshold
-- Try alternative detection methods
-
-### Best Practices
-
-**Standard workflow:**
-```python
-# 1. Clean signal
-cleaned = nk.ppg_clean(ppg_raw, sampling_rate=100, method='elgendi')
+Documented event fields include baseline/min/max/mean/SD rate, times, and polynomial
+trend coefficients. Interval output includes mean rate and HRV-family columns.
+Availability depends on input columns, duration, and release; inspect runtime output.
-# 2. Detect peaks with artifact correction
-peaks, info = nk.ppg_peaks(cleaned, sampling_rate=100, correct_artifacts=True)
+## Pulse morphology
-# 3. Assess quality
-quality = nk.ppg_quality(cleaned, sampling_rate=100)
+`ppg_segment()` returns a dict of pulse epochs. Morphology comparisons require:
-# 4. Comprehensive processing (alternative)
-signals, info = nk.ppg_process(ppg_raw, sampling_rate=100)
+- consistent site, attachment, pressure, wavelength, and polarity;
+- validated onsets/peaks and quality masks;
+- appropriate baseline/amplitude normalization;
+- sufficient sampling/bandwidth;
+- control of heart rate and vascular state; and
+- endpoint-specific evidence.
-# 5. Analyze
-analysis = nk.ppg_analyze(signals, sampling_rate=100)
-```
+A dicrotic feature in a processed waveform does not by itself validate aortic valve
+timing or arterial stiffness.
-**HRV from PPG:**
-```python
-# Process PPG signal
-signals, info = nk.ppg_process(ppg_raw, sampling_rate=100)
+## Interpretation boundary
-# Extract peaks and compute HRV
-hrv_indices = nk.hrv(info['PPG_Peaks'], sampling_rate=100)
+Use these tools for research and education. They are not validated here for arrhythmia,
+oxygen saturation, blood pressure, disease detection, remote patient monitoring,
+alarms, or wearable medical-device validation.
-# PPG-derived HRV is valid but may differ slightly from ECG-derived HRV
-# Differences due to pulse arrival time, vascular properties
-```
+## Sources checked 2026-07-23
-## Clinical and Research Applications
-
-**Wearable health monitoring:**
-- Consumer smartwatches and fitness trackers
-- Continuous heart rate monitoring
-- Sleep tracking and activity assessment
-
-**Clinical monitoring:**
-- Pulse oximetry (SpO₂ + heart rate)
-- Perioperative monitoring
-- Critical care heart rate assessment
-
-**Cardiovascular assessment:**
-- Pulse wave analysis
-- Arterial stiffness proxies (pulse arrival time)
-- Vascular aging indices
-
-**Autonomic function:**
-- HRV from PPG (PPG-HRV)
-- Stress and recovery monitoring
-- Mental workload assessment
-
-**Remote patient monitoring:**
-- Telemedicine applications
-- Home-based health tracking
-- Chronic disease management
-
-**Affective computing:**
-- Emotion recognition from physiological signals
-- User experience research
-- Human-computer interaction
-
-## PPG vs. ECG
-
-**Advantages of PPG:**
-- Non-invasive, no electrodes
-- Convenient for long-term monitoring
-- Low cost, miniaturizable
-- Suitable for wearables
-
-**Disadvantages of PPG:**
-- More susceptible to motion artifacts
-- Lower signal quality in poor perfusion
-- Pulse arrival time delay from heart
-- Cannot assess cardiac electrical activity
-
-**HRV comparison:**
-- PPG-HRV generally valid for time/frequency domains
-- May differ slightly due to pulse transit time variability
-- ECG preferred for clinical HRV when available
-- PPG acceptable for research and consumer applications
-
-## Interpretation Guidelines
-
-**Heart rate from PPG:**
-- Same interpretation as ECG-derived heart rate
-- Slight delay (pulse arrival time) is negligible for rate calculation
-- Motion artifacts more common: validate with signal quality
-
-**Pulse amplitude:**
-- Reflects peripheral perfusion
-- Increases: vasodilation, warmth
-- Decreases: vasoconstriction, cold, stress, poor contact
-
-**Pulse morphology:**
-- Systolic peak: Cardiac ejection
-- Dicrotic notch: Aortic valve closure, arterial compliance
-- Aging/stiffness: Earlier, more prominent dicrotic notch
-
-## References
-
-- Elgendi, M. (2012). On the analysis of fingertip photoplethysmogram signals. Current cardiology reviews, 8(1), 14-25.
-- Elgendi, M., Norton, I., Brearley, M., Abbott, D., & Schuurmans, D. (2013). Systolic peak detection in acceleration photoplethysmograms measured from emergency responders in tropical conditions. PloS one, 8(10), e76585.
-- Allen, J. (2007). Photoplethysmography and its application in clinical physiological measurement. Physiological measurement, 28(3), R1.
-- Tamura, T., Maeda, Y., Sekine, M., & Yoshida, M. (2014). Wearable photoplethysmographic sensors—past and present. Electronics, 3(2), 282-302.
+- [Official PPG API](https://neuropsychology.github.io/NeuroKit/functions/ppg.html)
+- [Stable v0.2.13 PPG source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/ppg)
+- [NeuroKit2 0.2.13 release](https://github.com/neuropsychology/NeuroKit/releases/tag/v0.2.13)
+- [Charlton et al. (2023), wearable PPG roadmap](https://doi.org/10.1088/1361-6579/acead2)
+- [Allen (2007), PPG measurement review](https://doi.org/10.1088/0967-3334/28/3/R01)
+- [Quigley et al. (2024), ECG/PPG and HRV guidance](https://doi.org/10.1111/psyp.14604)
+- [Yuda et al. (2020), PRV site differences](https://pmc.ncbi.nlm.nih.gov/articles/PMC7035641/)
diff --git a/skills/neurokit2/references/rsp.md b/skills/neurokit2/references/rsp.md
index 5d6b3a29..e06d8b92 100644
--- a/skills/neurokit2/references/rsp.md
+++ b/skills/neurokit2/references/rsp.md
@@ -1,510 +1,212 @@
-# Respiratory Signal Processing
+# Respiration
-## Overview
+Checked **2026-07-23** against NeuroKit2 0.2.13 stable runtime/source,
+the official RSP API/examples, and cardiorespiratory interpretation guidance.
-Respiratory signal processing in NeuroKit2 enables analysis of breathing patterns, respiratory rate, amplitude, and variability. Respiration is closely linked to cardiac activity (respiratory sinus arrhythmia), emotional state, and cognitive processes.
+## Acquisition contract and polarity
-## Main Processing Pipeline
+Record sensor type (belt, airflow, capnography, impedance, derived proxy), placement,
+gain/range, physical unit, native rate, clock, hardware filters, calibration, and
+annotations for speech, cough, sigh, breath hold, swallowing, movement, and detachment.
-### rsp_process()
+A belt/impedance amplitude is not tidal volume unless calibrated and validated.
+Different devices have opposite polarity. NeuroKit2's documented convention labels:
-Automated processing of respiratory signals with peak/trough detection and feature extraction.
+- `RSP_Peaks`: exhalation onsets;
+- `RSP_Troughs`: inhalation onsets; and
+- `RSP_Phase`: `1` inspiration, `0` expiration.
-```python
-signals, info = nk.rsp_process(rsp_signal, sampling_rate=100, method='khodadad2018')
-```
-
-**Pipeline steps:**
-1. Signal cleaning (noise removal, filtering)
-2. Peak (exhalation) and trough (inhalation) detection
-3. Respiratory rate calculation
-4. Amplitude computation
-5. Phase determination (inspiration/expiration)
-6. Respiratory volume per time (RVT)
-
-**Returns:**
-- `signals`: DataFrame with:
- - `RSP_Clean`: Filtered respiratory signal
- - `RSP_Peaks`, `RSP_Troughs`: Extrema markers
- - `RSP_Rate`: Instantaneous breathing rate (breaths/min)
- - `RSP_Amplitude`: Breath-to-breath amplitude
- - `RSP_Phase`: Inspiration (0) vs. expiration (1)
- - `RSP_Phase_Completion`: Phase completion percentage (0-1)
- - `RSP_RVT`: Respiratory volume per time
-- `info`: Dictionary with peak/trough indices
-
-**Methods:**
-- `'khodadad2018'`: Khodadad et al. algorithm (default, robust)
-- `'biosppy'`: BioSPPy-based processing (alternative)
-
-## Preprocessing Functions
-
-### rsp_clean()
-
-Remove noise and smooth respiratory signal.
-
-```python
-cleaned_rsp = nk.rsp_clean(rsp_signal, sampling_rate=100, method='khodadad2018')
-```
-
-**Methods:**
-
-**1. Khodadad2018 (default):**
-- Butterworth low-pass filter
-- Removes high-frequency noise
-- Preserves breathing waveform
-
-**2. BioSPPy:**
-- Alternative filtering approach
-- Similar performance to Khodadad
-
-**3. Hampel filter:**
-```python
-cleaned_rsp = nk.rsp_clean(rsp_signal, sampling_rate=100, method='hampel')
-```
-- Median-based outlier removal
-- Robust to artifacts and spikes
-- Preserves sharp transitions
-
-**Typical respiratory frequency:**
-- Adults at rest: 12-20 breaths/min (0.2-0.33 Hz)
-- Children: faster rates
-- During exercise: up to 40-60 breaths/min
-
-### rsp_peaks()
-
-Identify inhalation troughs and exhalation peaks in respiratory signal.
-
-```python
-peaks, info = nk.rsp_peaks(cleaned_rsp, sampling_rate=100, method='khodadad2018')
-```
-
-**Detection methods:**
-- `'khodadad2018'`: Optimized for clean signals
-- `'biosppy'`: Alternative approach
-- `'scipy'`: Simple scipy-based detection
-
-**Returns:**
-- Dictionary with:
- - `RSP_Peaks`: Indices of exhalation peaks (maximum points)
- - `RSP_Troughs`: Indices of inhalation troughs (minimum points)
-
-**Respiratory cycle definition:**
-- **Inhalation**: Trough → Peak (air flows in, chest/abdomen expands)
-- **Exhalation**: Peak → Trough (air flows out, chest/abdomen contracts)
+Verify these labels against the actual device and a known breath. Invert or relabel
+explicitly before interpretation if needed.
-### rsp_findpeaks()
-
-Low-level peak detection with multiple algorithm options.
+## Stable high-level pipeline
```python
-peaks_dict = nk.rsp_findpeaks(cleaned_rsp, sampling_rate=100, method='scipy')
+signals, info = nk.rsp_process(
+ rsp,
+ sampling_rate=50,
+ method="khodadad2018",
+ method_rvt="harrison2021",
+)
```
-**Methods:**
-- `'scipy'`: Scipy's find_peaks
-- Custom threshold-based algorithms
-
-**Use case:**
-- Fine-tuned peak detection
-- Custom parameter adjustment
-- Algorithm comparison
-
-### rsp_fixpeaks()
-
-Correct detected peak/trough anomalies (e.g., missed or false detections).
+Pinned default columns:
-```python
-corrected_peaks = nk.rsp_fixpeaks(peaks, sampling_rate=100)
+```text
+RSP_Raw, RSP_Clean, RSP_Amplitude, RSP_Rate, RSP_RVT,
+RSP_Phase, RSP_Phase_Completion,
+RSP_Symmetry_PeakTrough, RSP_Symmetry_RiseDecay,
+RSP_Peaks, RSP_Troughs
```
-**Corrections:**
-- Remove physiologically implausible intervals
-- Interpolate missing peaks
-- Remove artifact-related false peaks
-
-## Feature Extraction Functions
-
-### rsp_rate()
-
-Compute instantaneous breathing rate (breaths per minute).
-
-```python
-rate = nk.rsp_rate(peaks, sampling_rate=100, desired_length=None)
-```
-
-**Method:**
-- Calculate inter-breath intervals from peak/trough timing
-- Convert to breaths per minute (BPM)
-- Interpolate to match signal length
-
-**Typical values:**
-- Resting adult: 12-20 BPM
-- Slow breathing: <10 BPM (meditation, relaxation)
-- Fast breathing: >25 BPM (exercise, anxiety)
+`info` contained `RSP_Peaks`, `RSP_Troughs`, and `sampling_rate`. This is a
+default schema observation, not a universal contract.
-### rsp_amplitude()
-
-Compute breath-to-breath amplitude (peak-to-trough difference).
+## Cleaning and extrema
```python
-amplitude = nk.rsp_amplitude(cleaned_rsp, peaks)
+clean = nk.rsp_clean(rsp, sampling_rate=50, method="khodadad2018")
+markers, extrema = nk.rsp_peaks(
+ clean,
+ sampling_rate=50,
+ method="khodadad2018",
+)
```
-**Interpretation:**
-- Larger amplitude: deeper breaths (tidal volume increase)
-- Smaller amplitude: shallow breaths
-- Variable amplitude: irregular breathing pattern
+Stable peak methods include `khodadad2018`, `biosppy`, `scipy`, and
+`schafer2008`. `rsp_fixpeaks()` is currently documented as a placeholder that does
+not correct respiration extrema.
-**Clinical relevance:**
-- Reduced amplitude: restrictive lung disease, chest wall rigidity
-- Increased amplitude: compensatory hyperventilation
+Validate extrema during irregular breathing, pauses, speech, motion, and changing
+amplitude. A smooth sinusoidal simulation is not enough.
-### rsp_phase()
+## Rate, amplitude, and phase signatures
-Determine inspiration/expiration phases and completion percentage.
+These functions do not all accept the same peak object:
```python
-phase, completion = nk.rsp_phase(cleaned_rsp, peaks, sampling_rate=100)
+rate = nk.rsp_rate(
+ clean,
+ troughs=extrema["RSP_Troughs"],
+ sampling_rate=50,
+ method="trough",
+)
+amplitude = nk.rsp_amplitude(
+ clean,
+ peaks=extrema["RSP_Peaks"],
+ troughs=extrema["RSP_Troughs"],
+)
+phase = nk.rsp_phase(
+ extrema["RSP_Peaks"],
+ troughs=extrema["RSP_Troughs"],
+ desired_length=len(clean),
+)
```
-**Returns:**
-- `RSP_Phase`: Binary (0 = inspiration, 1 = expiration)
-- `RSP_Phase_Completion`: Continuous 0-1 indicating phase progress
-
-**Use cases:**
-- Respiratory-gated stimulus presentation
-- Phase-locked averaging
-- Respiratory-cardiac coupling analysis
+- `rsp_rate()` takes the cleaned signal first; `method="trough"` uses inhalation
+ onsets, while `method="xcorr"` estimates a windowed principal rate.
+- `rsp_amplitude()` returns a same-length interpolated amplitude series.
+- `rsp_phase()` takes peaks/troughs, not the cleaned signal, and returns a DataFrame
+ with phase and completion.
-### rsp_symmetry()
+Rates are breaths/minute. Amplitude remains in the sensor's arbitrary/calibrated unit.
+Phase accuracy depends on extrema and polarity.
-Analyze breath symmetry patterns (peak-trough balance, rise-decay timing).
+## RRV and RAV
```python
-symmetry = nk.rsp_symmetry(cleaned_rsp, peaks)
+rrv = nk.rsp_rrv(
+ signals["RSP_Rate"],
+ troughs=info["RSP_Troughs"],
+ sampling_rate=50,
+)
+rav = nk.rsp_rav(
+ signals["RSP_Amplitude"],
+ peaks=info,
+)
```
-**Metrics:**
-- Peak-trough symmetry: Are peaks and troughs equally spaced?
-- Rise-decay symmetry: Is inhalation time equal to exhalation time?
+The pinned `rsp_rrv()` output had 20 columns spanning interval, frequency, Poincaré,
+and entropy metrics (`RRV_RMSSD` through `RRV_SampEn`). The pinned RAV output had
+`RAV_Mean`, `RAV_SD`, `RAV_RMSSD`, and `RAV_CVSD`.
-**Interpretation:**
-- Symmetric: normal, relaxed breathing
-- Asymmetric: effortful breathing, airway obstruction
+Do not interpret RRV/RAV from only a few breaths. Choose duration from the lowest
+frequency and nonlinear metric being estimated, and report breath count, usable
+duration, irregular-breath exclusions, and sensitivity. There is no universal
+“higher is healthier” interpretation.
-## Advanced Analysis Functions
+## Respiratory volume per time
-### rsp_rrv()
+Direct stable signature:
-Respiratory Rate Variability - analogous to heart rate variability.
-
-```python
-rrv_indices = nk.rsp_rrv(peaks, sampling_rate=100)
+```text
+rsp_rvt(
+ rsp_signal, sampling_rate=1000, method="power2020",
+ boundaries=[2.0, 0.033333...], iterations=10, ...
+)
```
-**Time-domain metrics:**
-- `RRV_SDBB`: Standard deviation of breath-to-breath intervals
-- `RRV_RMSSD`: Root mean square of successive differences
-- `RRV_MeanBB`: Mean breath-to-breath interval
-
-**Frequency-domain metrics:**
-- Power in frequency bands (if applicable)
-
-**Interpretation:**
-- Higher RRV: flexible, adaptive breathing control
-- Lower RRV: rigid, constrained breathing
-- Altered RRV: anxiety, respiratory disorders, autonomic dysfunction
-
-**Recording duration:**
-- Minimum: 2-3 minutes
-- Optimal: 5-10 minutes for stable estimates
-
-### rsp_rvt()
-
-Respiratory Volume per Time - fMRI confound regressor.
+Direct `rsp_rvt()` defaults to `power2020`, while `rsp_process()` defaults its
+`method_rvt` to `harrison2021`. Other stable option: `birn2006`.
```python
-rvt = nk.rsp_rvt(cleaned_rsp, peaks, sampling_rate=100)
+rvt = nk.rsp_rvt(
+ clean,
+ sampling_rate=50,
+ method="harrison2021",
+)
```
-**Calculation:**
-- Derivative of respiratory signal
-- Captures rate of volume change
-- Correlates with BOLD signal fluctuations
+RVT is a derived proxy/regressor. It is not calibrated respiratory volume or minute
+ventilation. For fMRI nuisance modeling, match the cited definition, acquisition,
+lag/convolution, resampling, and scanner preprocessing; do not treat one method as
+interchangeable with another.
-**Use cases:**
-- fMRI artifact correction
-- Neuroimaging preprocessing
-- Respiratory confound regression
+## Missing data and artifacts
-**Reference:**
-- Birn, R. M., et al. (2008). Separating respiratory-variation-related fluctuations from neuronal-activity-related fluctuations in fMRI. NeuroImage, 31(4), 1536-1548.
+Respiration signals commonly contain nonstationary physiology. Do not automatically
+classify sighs, pauses, speech, coughing, or swallowing as noise. Annotate them according
+to the research question.
-### rsp_rav()
+- Segment long gaps/detachment.
+- Do not interpolate across apnea-like pauses or speech and then compute rate.
+- Preserve raw/clean/extrema overlays.
+- Track filter and window edge validity.
+- Quantify missing breaths and altered intervals after exclusions.
+- Verify belt slippage and baseline drift separately from breathing depth.
-Respiratory Amplitude Variability indices.
+## Event and interval analysis
```python
-rav = nk.rsp_rav(amplitude, sampling_rate=100)
+epochs = nk.epochs_create(
+ signals,
+ events,
+ sampling_rate=50,
+ epochs_start=-1,
+ epochs_end=8,
+ baseline_correction=False,
+)
+event_features = nk.rsp_eventrelated(epochs)
+interval_features = nk.rsp_intervalrelated(signals, sampling_rate=50)
```
-**Metrics:**
-- Standard deviation of amplitudes
-- Coefficient of variation
-- Range of amplitudes
-
-**Interpretation:**
-- High RAV: irregular depth (sighing, arousal changes)
-- Low RAV: stable, controlled breathing
+Event-related features are conditional and include rate/amplitude baselines and
+post-event summaries, phase/completion at onset, and RVT fields when present. Interval
+analysis can append RRV/RAV and inspiration/expiration duration features. Inspect the
+runtime schema.
-## Analysis Functions
+Baseline subtraction is usually inappropriate for binary phase/peak columns. Prespecify
+which continuous features, if any, are baseline corrected.
-### rsp_analyze()
+## RSA and alignment
-Automatically select event-related or interval-related analysis.
+For RSA, ECG and respiration need a shared clock and verified lag/drift:
```python
-analysis = nk.rsp_analyze(signals, sampling_rate=100)
+rsa = nk.hrv_rsa(
+ ecg_signals,
+ rsp_signals,
+ rpeaks=ecg_info,
+ sampling_rate=common_rate,
+ continuous=False,
+)
```
-**Mode selection:**
-- Duration < 10 seconds → event-related
-- Duration ≥ 10 seconds → interval-related
+Measure and report respiration; spontaneous or paced breathing changes the estimand.
+RSA can reflect cardiac vagal modulation under suitable conditions but is confounded by
+respiratory parameters, activity, posture, age, and adrenergic influence.
-### rsp_eventrelated()
+## Interpretation boundary
-Analyze respiratory responses to specific events/stimuli.
-
-```python
-results = nk.rsp_eventrelated(epochs)
-```
+Use this module for respiratory time-series research. It is not a validated system for
+apnea detection, capnography, tidal-volume measurement, respiratory diagnosis,
+biofeedback safety, patient/driver monitoring, or ventilatory control.
-**Computed metrics (per epoch):**
-- `RSP_Rate_Mean`: Average breathing rate during epoch
-- `RSP_Rate_Min/Max`: Minimum/maximum rate
-- `RSP_Amplitude_Mean`: Average breath depth
-- `RSP_Phase`: Respiratory phase at event onset
-- Dynamics of rate and amplitude across epoch
-
-**Use cases:**
-- Respiratory changes during emotional stimuli
-- Anticipatory breathing before task events
-- Breath-holding or hyperventilation paradigms
-
-### rsp_intervalrelated()
-
-Analyze extended respiratory recordings.
-
-```python
-results = nk.rsp_intervalrelated(signals, sampling_rate=100)
-```
-
-**Computed metrics:**
-- `RSP_Rate_Mean`: Average breathing rate
-- `RSP_Rate_SD`: Variability in rate
-- `RSP_Amplitude_Mean`: Average breath depth
-- RRV indices (if sufficient data)
-- RAV indices
-
-**Recording duration:**
-- Minimum: 60 seconds
-- Optimal: 5-10 minutes
-
-**Use cases:**
-- Resting state breathing patterns
-- Baseline respiratory assessment
-- Stress or relaxation monitoring
-
-## Simulation and Visualization
-
-### rsp_simulate()
-
-Generate synthetic respiratory signals for testing.
-
-```python
-synthetic_rsp = nk.rsp_simulate(duration=60, sampling_rate=100, respiratory_rate=15,
- method='sinusoidal', noise=0.1, random_state=42)
-```
-
-**Methods:**
-- `'sinusoidal'`: Simple sinusoidal oscillation (fast)
-- `'breathmetrics'`: Advanced realistic breathing model (slower, more accurate)
-
-**Parameters:**
-- `respiratory_rate`: Breaths per minute (default: 15)
-- `noise`: Gaussian noise level
-- `random_state`: Seed for reproducibility
-
-**Use cases:**
-- Algorithm validation
-- Parameter tuning
-- Educational demonstrations
-
-### rsp_plot()
-
-Visualize processed respiratory signal.
-
-```python
-nk.rsp_plot(signals, info, static=True)
-```
-
-**Displays:**
-- Raw and cleaned respiratory signal
-- Detected peaks and troughs
-- Instantaneous breathing rate
-- Phase markers
-
-**Interactive mode:** Set `static=False` for Plotly visualization
-
-## Practical Considerations
-
-### Sampling Rate Recommendations
-- **Minimum**: 10 Hz (adequate for rate estimation)
-- **Standard**: 50-100 Hz (research-grade)
-- **High-resolution**: 1000 Hz (typically unnecessary, oversampled)
-
-### Recording Duration
-- **Rate estimation**: ≥10 seconds (few breaths)
-- **RRV analysis**: ≥2-3 minutes
-- **Resting state**: 5-10 minutes
-- **Circadian patterns**: Hours to days
-
-### Signal Acquisition Methods
-
-**Strain gauge/piezoelectric belt:**
-- Chest or abdominal expansion
-- Most common
-- Comfortable, non-invasive
-
-**Thermistor/thermocouple:**
-- Nasal/oral airflow temperature
-- Direct airflow measurement
-- Can be intrusive
-
-**Capnography:**
-- End-tidal CO₂ measurement
-- Gold standard for physiology
-- Expensive, clinical settings
-
-**Impedance pneumography:**
-- Derived from ECG electrodes
-- Convenient for multi-modal recording
-- Less accurate than dedicated sensors
-
-### Common Issues and Solutions
-
-**Irregular breathing:**
-- Normal in awake, resting humans
-- Sighs, yawns, speech, swallowing cause variability
-- Exclude artifacts or model as events
-
-**Shallow breathing:**
-- Low signal amplitude
-- Check sensor placement and tightness
-- Increase gain if available
-
-**Movement artifacts:**
-- Spikes or discontinuities
-- Minimize participant movement
-- Use robust peak detection (Hampel filter)
-
-**Talking/coughing:**
-- Disrupts natural breathing pattern
-- Annotate and exclude from analysis
-- Or model as separate event types
-
-### Best Practices
-
-**Standard workflow:**
-```python
-# 1. Clean signal
-cleaned = nk.rsp_clean(rsp_raw, sampling_rate=100, method='khodadad2018')
-
-# 2. Detect peaks/troughs
-peaks, info = nk.rsp_peaks(cleaned, sampling_rate=100)
-
-# 3. Extract features
-rate = nk.rsp_rate(peaks, sampling_rate=100, desired_length=len(cleaned))
-amplitude = nk.rsp_amplitude(cleaned, peaks)
-phase = nk.rsp_phase(cleaned, peaks, sampling_rate=100)
-
-# 4. Comprehensive processing (alternative)
-signals, info = nk.rsp_process(rsp_raw, sampling_rate=100)
-
-# 5. Analyze
-analysis = nk.rsp_analyze(signals, sampling_rate=100)
-```
-
-**Respiratory-cardiac integration:**
-```python
-# Process both signals
-ecg_signals, ecg_info = nk.ecg_process(ecg, sampling_rate=1000)
-rsp_signals, rsp_info = nk.rsp_process(rsp, sampling_rate=100)
-
-# Respiratory sinus arrhythmia (RSA)
-rsa = nk.hrv_rsa(ecg_info['ECG_R_Peaks'], rsp_signals['RSP_Clean'], sampling_rate=1000)
-
-# Or use bio_process for multi-signal integration
-bio_signals, bio_info = nk.bio_process(ecg=ecg, rsp=rsp, sampling_rate=1000)
-```
+## Sources checked 2026-07-23
-## Clinical and Research Applications
-
-**Psychophysiology:**
-- Emotion and arousal (rapid, shallow breathing during stress)
-- Relaxation interventions (slow, deep breathing)
-- Respiratory biofeedback
-
-**Anxiety and panic disorders:**
-- Hyperventilation during panic attacks
-- Altered breathing patterns
-- Breathing retraining therapy effectiveness
-
-**Sleep medicine:**
-- Sleep apnea detection
-- Breathing pattern abnormalities
-- Sleep stage correlates
-
-**Cardiorespiratory coupling:**
-- Respiratory sinus arrhythmia (HRV modulation by breathing)
-- Heart-lung interaction
-- Autonomic nervous system assessment
-
-**Neuroimaging:**
-- fMRI artifact correction (RVT regressor)
-- BOLD signal confound removal
-- Respiratory-related brain activity
-
-**Meditation and mindfulness:**
-- Breath awareness training
-- Slow breathing practices (resonance frequency ~6 breaths/min)
-- Physiological markers of relaxation
-
-**Athletic performance:**
-- Breathing efficiency
-- Training adaptations
-- Recovery monitoring
-
-## Interpretation Guidelines
-
-**Breathing rate:**
-- **Normal**: 12-20 BPM (adults at rest)
-- **Slow**: <10 BPM (relaxation, meditation, sleep)
-- **Fast**: >25 BPM (exercise, anxiety, pain, fever)
-
-**Breathing amplitude:**
-- Tidal volume typically 400-600 mL at rest
-- Deep breathing: 2-3 L
-- Shallow breathing: <300 mL
-
-**Respiratory patterns:**
-- **Normal**: Smooth, regular sinusoidal
-- **Cheyne-Stokes**: Crescendo-decrescendo with apneas (clinical pathology)
-- **Ataxic**: Completely irregular (brainstem lesion)
-
-## References
-
-- Khodadad, D., Nordebo, S., Müller, B., Waldmann, A., Yerworth, R., Becher, T., ... & Bayford, R. (2018). A review of tissue substitutes for ultrasound imaging. Ultrasound in medicine & biology, 44(9), 1807-1823.
-- Grossman, P., & Taylor, E. W. (2007). Toward understanding respiratory sinus arrhythmia: Relations to cardiac vagal tone, evolution and biobehavioral functions. Biological psychology, 74(2), 263-285.
-- Birn, R. M., Diamond, J. B., Smith, M. A., & Bandettini, P. A. (2006). Separating respiratory-variation-related fluctuations from neuronal-activity-related fluctuations in fMRI. NeuroImage, 31(4), 1536-1548.
+- [Official RSP API](https://neuropsychology.github.io/NeuroKit/functions/rsp.html)
+- [Official RRV example](https://neuropsychology.github.io/NeuroKit/examples/rsp_rrv/rsp_rrv.html)
+- [Stable v0.2.13 RSP source](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/rsp)
+- [Grossman & Taylor (2007), respiration/RSA caveats](https://doi.org/10.1016/j.biopsycho.2005.11.014)
+- [Berntson et al. (1997), HRV origins/methods/caveats](https://doi.org/10.1111/j.1469-8986.1997.tb02140.x)
+- [Birn et al. (2006), RVT and fMRI](https://doi.org/10.1016/j.neuroimage.2005.11.053)
diff --git a/skills/neurokit2/references/signal_processing.md b/skills/neurokit2/references/signal_processing.md
index 41837107..36f472d1 100644
--- a/skills/neurokit2/references/signal_processing.md
+++ b/skills/neurokit2/references/signal_processing.md
@@ -1,648 +1,160 @@
-# General Signal Processing
+# General signal processing
+
+Checked **2026-07-23** against NeuroKit2 0.2.13, its stable wheel, tagged
+source, and the live signal API page (`0.2.13.dev214`).
+
+## Start with a signal contract
+
+For every channel retain:
+
+- sensor/channel identity and physical unit;
+- native sampling rate and timestamps;
+- polarity, gain, acquisition filters, and ADC range;
+- missing/discontinuous intervals and artifact annotations;
+- expected physiological bandwidth; and
+- the exact NeuroKit2 function, method, parameters, and package version.
+
+`signal_sanitize()` does **not** clean artifacts or interpolate missing values. In
+0.2.13 it resets an indexed pandas Series to a default index.
+
+## Safe preprocessing order
-## Overview
+1. Preserve the original samples and time axis.
+2. Check timestamp order, rate, clipping, flatlines, non-finite values, and gaps.
+3. Split at long gaps. Interpolate only short, prespecified gaps and retain a mask.
+4. Remove offsets/trends only when justified.
+5. Apply a modality/method-specific filter at the native rate.
+6. Trim or flag filter transients.
+7. Detect/correct peaks or derive features.
+8. Resample continuous outputs only when alignment or modeling requires it.
-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.
+Do not use a filter to “fix” clipping, sensor detachment, dropped packets, or motion.
+Do not interpolate event markers, quality flags, or peak indicator vectors as
+continuous amplitudes.
+
+## Verified 0.2.13 interfaces
+
+| Function | Stable behavior relevant to schemas |
+|---|---|
+| `signal_filter()` | Returns one array. Default is order-2 Butterworth; available behavior depends on `method`, cutoffs, and sampling rate. |
+| `signal_sanitize()` | Resets pandas Series indexing; it is not a NaN/artifact cleaner. |
+| `signal_fillmissing()` | Forward, backward, or both-direction fill only (`method="forward"`, `"backward"`, or `"both"`). |
+| `signal_resample()` | Returns one array; accepts target length or source/target rates. Methods include interpolation, FFT, polyphase, NumPy, and pandas paths. |
+| `signal_interpolate()` | Returns interpolated values; explicitly provide source and target coordinates for irregular time. |
+| `signal_findpeaks()` | Returns a dict. The pinned default synthetic probe observed `Peaks`, `Height`, `Distance`, `Onsets`, `Offsets`, and `Width`; keys can change with input/method. |
+| `signal_fixpeaks()` | Returns `(info, corrected_peaks)` in stable source. Default Kubios `info` includes artifact categories and diagnostics. |
+| `signal_period()` | Takes peak locations and returns period in seconds, optionally interpolated to a requested sample length. |
+| `signal_rate()` | Takes peak locations and returns events/minute, optionally interpolated. |
+| `signal_psd()` | Returns a DataFrame; the pinned Welch probe observed `Frequency` and `Power`. |
+| `signal_power()` | Returns a one-row DataFrame with band-derived names such as `Hz_0.5_2`; names depend on requested bands. |
+| `signal_timefrequency()` | Returns `(frequency, time, representation)`; frequency is the first object. |
+| `signal_synchrony()` | Returns an array; supported methods are Hilbert phase synchrony and rolling correlation. |
+| `signal_decompose()` | Returns a component array; stable methods are EMD and SSA, not a component dictionary. |
+| `signal_changepoints()` | Implements PELT and returns change-point sample indices. |
-## Preprocessing Functions
-
-### signal_filter()
-
-Apply frequency-domain filtering to remove noise or isolate frequency bands.
-
-```python
-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):
-```python
-lowpass = nk.signal_filter(signal, sampling_rate=1000, highcut=50)
-```
-- Removes frequencies above highcut
-- Smooths signal, removes high-frequency noise
-
-**Highpass** (lowcut only):
-```python
-highpass = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5)
-```
-- Removes frequencies below lowcut
-- Removes baseline drift, DC offset
-
-**Bandpass** (both lowcut and highcut):
-```python
-bandpass = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5, highcut=50)
-```
-- Retains frequencies between lowcut and highcut
-- Isolates specific frequency band
-
-**Bandstop/Notch** (powerline removal):
-```python
-notch = nk.signal_filter(signal, sampling_rate=1000, method='powerline', powerline=50)
-```
-- Removes 50 or 60 Hz powerline noise
-- Narrow notch filter
-
-**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 Hz
-
-**Order parameter:**
-- Higher order: Steeper transition, more ringing
-- Lower order: Gentler transition, less ringing
-- Typical: 2-5 for physiological signals
-
-### signal_sanitize()
-
-Remove invalid values (NaN, inf) and optionally interpolate.
-
-```python
-clean_signal = nk.signal_sanitize(signal, interpolate=True)
-```
-
-**Use cases:**
-- Handle missing data points
-- Remove artifacts marked as NaN
-- Prepare signal for algorithms requiring continuous data
-
-### signal_resample()
-
-Change sampling rate of signal (upsample or downsample).
-
-```python
-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:**
-- Match sampling rates across multi-modal recordings
-- Reduce data size (downsample)
-- Increase temporal resolution (upsample)
-
-### signal_fillmissing()
-
-Interpolate missing or invalid data points.
-
-```python
-filled = nk.signal_fillmissing(signal, method='linear')
-```
-
-**Methods:**
-- `'linear'`: Linear interpolation
-- `'nearest'`: Nearest neighbor
-- `'pad'`: Forward/backward fill
-- `'cubic'`: Cubic spline
-- `'polynomial'`: Polynomial fitting
-
-## Transformation Functions
-
-### signal_detrend()
-
-Remove slow trends from signal.
-
-```python
-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 detrending
-
-**Use cases:**
-- Remove baseline drift
-- Stabilize mean before analysis
-- Prepare for stationarity-assuming algorithms
-
-### signal_decompose()
-
-Decompose signal into constituent components.
-
-```python
-components = nk.signal_decompose(signal, sampling_rate=1000, method='emd')
-```
-
-**Methods:**
-
-**Empirical Mode Decomposition (EMD):**
-```python
-components = nk.signal_decompose(signal, sampling_rate=1000, method='emd')
-```
-- Data-adaptive decomposition into Intrinsic Mode Functions (IMFs)
-- Each IMF represents different frequency content (high to low)
-- No predefined basis functions
-
-**Singular Spectrum Analysis (SSA):**
-```python
-components = nk.signal_decompose(signal, method='ssa')
-```
-- Decomposes into trend, oscillations, and noise
-- Based on eigenvalue decomposition of trajectory matrix
-
-**Wavelet decomposition:**
-- Time-frequency representation
-- Localized in both time and frequency
-
-**Returns:**
-- Dictionary with component signals
-- Trend, oscillatory components, residual
-
-**Use cases:**
-- Isolate physiological rhythms
-- Separate signal from noise
-- Multi-scale analysis
-
-### signal_recompose()
-
-Reconstruct signal from decomposed components.
-
-```python
-reconstructed = nk.signal_recompose(components, indices=[1, 2, 3])
-```
-
-**Use case:**
-- Selective reconstruction after decomposition
-- Remove specific IMFs or components
-- Adaptive filtering
-
-### signal_binarize()
-
-Convert continuous signal to binary (0/1) based on threshold.
-
-```python
-binary = nk.signal_binarize(signal, method='threshold', threshold=0.5)
-```
-
-**Methods:**
-- `'threshold'`: Simple threshold
-- `'median'`: Median-based
-- `'mean'`: Mean-based
-- `'quantile'`: Percentile-based
-
-**Use case:**
-- Event detection from continuous signal
-- Trigger extraction
-- State classification
-
-### signal_distort()
-
-Add controlled noise or artifacts for testing.
-
-```python
-distorted = nk.signal_distort(signal, sampling_rate=1000, noise_amplitude=0.1,
- noise_frequency=50, artifacts_amplitude=0.5)
-```
-
-**Parameters:**
-- `noise_amplitude`: Gaussian noise level
-- `noise_frequency`: Sinusoidal interference (e.g., powerline)
-- `artifacts_amplitude`: Random spike artifacts
-- `artifacts_number`: Number of artifacts to add
-
-**Use cases:**
-- Algorithm robustness testing
-- Preprocessing method evaluation
-- Realistic data simulation
-
-### signal_interpolate()
-
-Interpolate signal at new time points or fill gaps.
-
-```python
-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 monotonicity
-
-**Use case:**
-- Convert irregular samples to regular grid
-- Upsample for visualization
-- Align signals with different time bases
-
-### signal_merge()
-
-Combine multiple signals with different sampling rates.
-
-```python
-merged = nk.signal_merge(signal1, signal2, time1=None, time2=None, sampling_rate=None)
-```
-
-**Use case:**
-- Multi-modal signal integration
-- Combine data from different devices
-- Synchronize based on timestamps
-
-### signal_flatline()
-
-Identify periods of constant signal (artifacts or sensor failure).
-
-```python
-flatline_mask = nk.signal_flatline(signal, duration=5.0, sampling_rate=1000)
-```
-
-**Returns:**
-- Binary mask where True indicates flatline periods
-- Duration threshold prevents false positives from normal stability
-
-### signal_noise()
-
-Add various types of noise to signal.
-
-```python
-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)
-
-### signal_surrogate()
-
-Generate surrogate signals preserving certain properties.
-
-```python
-surrogate = nk.signal_surrogate(signal, method='IAAFT')
-```
-
-**Methods:**
-- `'IAAFT'`: Iterated Amplitude Adjusted Fourier Transform
- - Preserves amplitude distribution and power spectrum
-- `'random_shuffle'`: Random permutation (null hypothesis testing)
-
-**Use case:**
-- Nonlinearity testing
-- Null hypothesis generation for statistical tests
-
-## Peak Detection and Correction
-
-### signal_findpeaks()
-
-Detect local maxima (peaks) in signal.
-
-```python
-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 thresholds
-- `relative_height_min/max`: Relative to signal range (0-1)
-- `threshold`: Minimum prominence
-- `distance`: Minimum samples between peaks
-
-**Returns:**
-- Dictionary with:
- - `'Peaks'`: Peak indices
- - `'Height'`: Peak amplitudes
- - `'Distance'`: Inter-peak intervals
-
-**Use cases:**
-- Generic peak detection for any signal
-- R-peaks, respiratory peaks, pulse peaks
-- Event detection
-
-### signal_fixpeaks()
-
-Correct detected peaks for artifacts and anomalies.
-
-```python
-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 approach
-
-**Corrections:**
-- Remove physiologically implausible intervals
-- Interpolate missing peaks
-- Remove extra detected peaks (duplicates)
-
-**Use case:**
-- Artifact correction in R-R intervals
-- Improve HRV analysis quality
-- Respiratory or pulse peak correction
-
-## Analysis Functions
-
-### signal_rate()
-
-Compute instantaneous rate from event occurrences (peaks).
-
-```python
-rate = nk.signal_rate(peaks, sampling_rate=1000, desired_length=None)
-```
-
-**Method:**
-- Calculate inter-event intervals
-- Convert to events per minute
-- Interpolate to match desired length
-
-**Use case:**
-- Heart rate from R-peaks
-- Breathing rate from respiratory peaks
-- Any periodic event rate
-
-### signal_period()
-
-Find dominant period/frequency in signal.
-
-```python
-period = nk.signal_period(signal, sampling_rate=1000, method='autocorrelation',
- show=False)
-```
-
-**Methods:**
-- `'autocorrelation'`: Peak in autocorrelation function
-- `'powerspectraldensity'`: Peak in frequency spectrum
-
-**Returns:**
-- Period in samples or seconds
-- Frequency (1/period) in Hz
-
-**Use case:**
-- Detect dominant rhythm
-- Estimate fundamental frequency
-- Breathing rate, heart rate estimation
-
-### signal_phase()
-
-Compute instantaneous phase of signal.
-
-```python
-phase = nk.signal_phase(signal, method='hilbert')
-```
-
-**Methods:**
-- `'hilbert'`: Hilbert transform (analytic signal)
-- `'wavelet'`: Wavelet-based phase
-
-**Returns:**
-- Phase in radians (-π to π) or 0 to 1 (normalized)
-
-**Use cases:**
-- Phase-locked analysis
-- Synchronization measures
-- Phase-amplitude coupling
-
-### signal_psd()
-
-Compute Power Spectral Density.
-
-```python
-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:**
-- Frequency content analysis
-- HRV frequency domain
-- Spectral signatures
-
-### signal_power()
-
-Compute power in specific frequency bands.
-
-```python
-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:**
-- Dictionary with absolute and relative power per band
-- Peak frequencies
-
-**Use case:**
-- HRV frequency analysis
-- EEG band power
-- Rhythm quantification
-
-### signal_autocor()
-
-Compute autocorrelation function.
-
-```python
-autocorr = nk.signal_autocor(signal, lag=1000, show=False)
-```
-
-**Interpretation:**
-- High autocorrelation at lag: signal repeats every lag samples
-- Periodic signals: peaks at multiples of period
-- Random signals: rapid decay to zero
-
-**Use cases:**
-- Detect periodicity
-- Assess temporal structure
-- Memory in signal
-
-### signal_zerocrossings()
-
-Count zero crossings (sign changes).
-
-```python
-n_crossings = nk.signal_zerocrossings(signal)
-```
-
-**Interpretation:**
-- More crossings: higher frequency content
-- Related to dominant frequency (rough estimate)
-
-**Use case:**
-- Simple frequency estimation
-- Signal regularity assessment
-
-### signal_changepoints()
-
-Detect abrupt changes in signal properties (mean, variance).
-
-```python
-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:**
-- Indices of detected changepoints
-- Segments between changepoints
-
-**Use cases:**
-- Segment signal into states
-- Detect transitions (e.g., sleep stages, arousal states)
-- Automatic epoch definition
-
-### signal_synchrony()
-
-Assess synchronization between two signals.
-
-```python
-sync = nk.signal_synchrony(signal1, signal2, method='correlation')
-```
-
-**Methods:**
-- `'correlation'`: Pearson correlation
-- `'coherence'`: Frequency-domain coherence
-- `'mutual_information'`: Information-theoretic measure
-- `'phase'`: Phase locking value
-
-**Use cases:**
-- Heart-brain coupling
-- Inter-brain synchrony
-- Multi-channel coordination
-
-### signal_smooth()
-
-Apply smoothing to reduce noise.
+Never unpack `signal_psd()` into `(psd, frequencies)` in 0.2.13:
```python
-smoothed = nk.signal_smooth(signal, method='convolution', kernel='boxzen', size=10)
+psd = nk.signal_psd(
+ signal,
+ sampling_rate=250,
+ method="welch",
+ normalize=False,
+ show=False,
+)
+frequency_hz = psd["Frequency"]
+power = psd["Power"]
```
-**Methods:**
-- `'convolution'`: Apply kernel (boxcar, Gaussian, etc.)
-- `'median'`: Median filter (robust to outliers)
-- `'savgol'`: Savitzky-Golay filter (preserves peaks)
-- `'loess'`: Locally weighted regression
+`normalize=True` scales by maximum PSD power. It is not physical calibration. Use
+`normalize=False` when absolute spectral units are required and derive those units from
+the acquisition and estimator.
-**Kernel types (for convolution):**
-- `'boxcar'`: Simple moving average
-- `'gaussian'`: Gaussian-weighted average
-- `'hann'`, `'hamming'`, `'blackman'`: Windowing functions
+## Filtering and resampling
-**Use cases:**
-- Noise reduction
-- Trend extraction
-- Visualization enhancement
+Cutoffs are in Hz and must lie below Nyquist. Report:
-### signal_timefrequency()
+- filter family and implementation (`butterworth`, FIR, Savitzky–Golay, powerline);
+- order, low/high cutoff, notch frequency, and whether processing is zero phase;
+- padding/edge handling and samples discarded; and
+- source and target sampling rates plus resampling method.
-Time-frequency representation (spectrogram).
+Example:
```python
-tf, time, freq = nk.signal_timefrequency(signal, sampling_rate=1000, method='stft',
- max_frequency=50, show=False)
+filtered = nk.signal_filter(
+ signal,
+ sampling_rate=250,
+ lowcut=0.5,
+ highcut=40,
+ method="butterworth",
+ order=2,
+)
+resampled = nk.signal_resample(
+ filtered,
+ sampling_rate=250,
+ desired_sampling_rate=100,
+ method="poly",
+)
```
-**Methods:**
-- `'stft'`: Short-Time Fourier Transform
-- `'cwt'`: Continuous Wavelet Transform
-
-**Returns:**
-- `tf`: Time-frequency matrix (power at each time-frequency point)
-- `time`: Time bins
-- `freq`: Frequency bins
+Downsampling requires anti-alias filtering. Resampling cannot recover timing precision or
+bandwidth absent from the acquisition. For multimodal data, preserve native processing
+and timestamps first; choose a common grid only after clock alignment.
-**Use cases:**
-- Non-stationary signal analysis
-- Time-varying frequency content
-- EEG/MEG time-frequency analysis
+## Missing data
-## Simulation
+Forward/backward fill can create artificial constant segments. Generic interpolation can
+create smooth but fictional morphology and peaks. Record:
+
+- count and maximum run of missing samples;
+- gap durations in seconds;
+- whether each gap was segmented, excluded, padded, or interpolated;
+- interpolation method and maximum allowed gap; and
+- whether downstream quality and uncertainty include the imputed mask.
-### signal_simulate()
+Most modality pipelines may warn and internally forward-fill some missing samples. That
+convenience is not a study-level missing-data policy.
-Generate various synthetic signals for testing.
-
-```python
-signal = nk.signal_simulate(duration=10, sampling_rate=1000, frequency=[5, 10],
- amplitude=[1.0, 0.5], noise=0.1)
+## Peak correction
+
+```python
+info, corrected = nk.signal_fixpeaks(
+ peaks,
+ sampling_rate=250,
+ method="Kubios",
+ iterative=True,
+)
```
-**Signal types:**
-- Sinusoidal oscillations (specify frequencies)
-- Multiple frequency components
-- Gaussian noise
-- Combinations
+The Kubios/Lipponen–Tarvainen path is intended for ECG/PPG beats. `method="neurokit"`
+supports explicit interval limits and can be used more generically. Always retain raw
+and corrected peaks, counts by artifact category, affected time ranges, and results with
+and without correction. Do not call corrected beat intervals “normal-to-normal” unless
+the study actually identifies non-sinus/ectopic beats.
-**Use cases:**
-- Algorithm testing
-- Method validation
-- Educational demonstrations
+## Quality and reproducibility
+
+Useful QC is multimodal and method-specific:
-## Visualization
+- raw/clean overlays and filter-edge review;
+- missing, flatline, clipping, and saturation fractions;
+- peak/onset overlays and interval distributions;
+- quality values with their method-specific direction and scale;
+- sensitivity to plausible filter/detector settings; and
+- synthetic fixtures plus labeled empirical validation data.
-### signal_plot()
+The bundled inspector is dependency-free:
-Visualize signal and optional markers.
-
-```python
-nk.signal_plot(signal, sampling_rate=1000, peaks=None, show=True)
+```bash
+python skills/neurokit2/scripts/inspect_signal.py \
+ --input signal.csv --root . --deidentified \
+ --columns ECG --time-column time_s --units ECG=mV
```
-**Features:**
-- Time axis in seconds
-- Peak markers
-- Multiple subplots for signal arrays
-
-## Practical Tips
-
-**Choosing filter parameters:**
-- **Lowcut**: Set below lowest frequency of interest
-- **Highcut**: Set above highest frequency of interest
-- **Order**: Start with 2-5, increase if transition too slow
-- **Method**: Butterworth is safe default
-
-**Handling edge effects:**
-- Filtering introduces artifacts at signal edges
-- Pad signal before filtering, then trim
-- Or discard initial/final seconds
-
-**Dealing with gaps:**
-- Small gaps: `signal_fillmissing()` with interpolation
-- Large gaps: Segment signal, analyze separately
-- Mark gaps as NaN, use interpolation carefully
-
-**Combining operations:**
-```python
-# 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:**
-- Filtering: FFT-based methods faster for long signals
-- Resampling: Downsample early in pipeline to speed up
-- Large datasets: Process in chunks if memory-limited
-
-## References
+## Sources checked 2026-07-23
-- Virtanen, P., et al. (2020). SciPy 1.0: fundamental algorithms for scientific computing in Python. Nature methods, 17(3), 261-272.
-- Tarvainen, M. P., Ranta-aho, P. O., & Karjalainen, P. A. (2002). An advanced detrending method with application to HRV analysis. IEEE Transactions on Biomedical Engineering, 49(2), 172-175.
-- Huang, N. E., et al. (1998). The empirical mode decomposition and the Hilbert spectrum for nonlinear and non-stationary time series analysis. Proceedings of the Royal Society of London A, 454(1971), 903-995.
+- [Official signal API](https://neuropsychology.github.io/NeuroKit/functions/signal.html)
+- [Stable v0.2.13 source tag](https://github.com/neuropsychology/NeuroKit/tree/v0.2.13/neurokit2/signal)
+- [NeuroKit2 main paper](https://doi.org/10.3758/s13428-020-01516-y)
+- [Lipponen & Tarvainen (2019), peak correction](https://doi.org/10.1080/03091902.2019.1640306)
diff --git a/skills/neurokit2/scripts/_common.py b/skills/neurokit2/scripts/_common.py
new file mode 100644
index 00000000..f3e546e4
--- /dev/null
+++ b/skills/neurokit2/scripts/_common.py
@@ -0,0 +1,567 @@
+#!/usr/bin/env python3
+"""Shared bounded, local-only helpers for the NeuroKit2 skill CLIs."""
+
+from __future__ import annotations
+
+import csv
+import hashlib
+import io
+import json
+import math
+import os
+import stat
+import tempfile
+from collections.abc import Iterable, Mapping, Sequence
+from pathlib import Path
+from typing import Any
+
+NEUROKIT2_VERSION = "0.2.13"
+PINNED_INSTALL = 'uv pip install "neurokit2==0.2.13"'
+MAX_CSV_BYTES = 64 * 1024 * 1024
+MAX_JSON_BYTES = 4 * 1024 * 1024
+MAX_OUTPUT_BYTES = 128 * 1024 * 1024
+MAX_ROWS = 500_000
+MAX_CHANNELS = 64
+MAX_SELECTED_COLUMNS = 16
+MAX_CELL_CHARS = 4096
+MISSING_TOKENS = {"", "na", "n/a", "nan", "none", "null"}
+
+
+class CliError(ValueError):
+ """An expected command-line validation error."""
+
+
+def _reject_constant(value: str) -> None:
+ raise CliError(f"non-standard JSON constant is not allowed: {value}")
+
+
+def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise CliError(f"duplicate JSON key is not allowed: {key!r}")
+ result[key] = value
+ return result
+
+
+def _reject_url(value: str) -> None:
+ lowered = value.strip().lower()
+ if "://" in lowered or lowered.startswith(
+ ("http:", "https:", "ftp:", "s3:", "gs:", "file:")
+ ):
+ raise CliError("URLs are not accepted; provide a bounded local path")
+ if "\x00" in value:
+ raise CliError("paths must not contain a NUL byte")
+
+
+def _absolute_lexical(path: Path) -> Path:
+ return Path(os.path.abspath(os.fspath(path)))
+
+
+def _reject_symlink_components(path: Path) -> None:
+ absolute = _absolute_lexical(path)
+ current = Path(absolute.anchor)
+ for part in absolute.parts[1:]:
+ current /= part
+ try:
+ if current.is_symlink():
+ raise CliError(f"symlink paths are not accepted: {current.name!r}")
+ except OSError as exc:
+ raise CliError(
+ f"cannot inspect path component {current.name!r}: {exc}"
+ ) from exc
+
+
+def checked_root(value: str | os.PathLike[str]) -> Path:
+ """Return an existing, non-symlink directory used as an I/O boundary."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ supplied = _absolute_lexical(Path(raw).expanduser())
+ if supplied.is_symlink():
+ raise CliError("root directory must not itself be a symlink")
+ try:
+ root = supplied.resolve(strict=True)
+ info = root.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access root directory: {exc}") from exc
+ if not stat.S_ISDIR(info.st_mode):
+ raise CliError("root must be an existing directory")
+ _reject_symlink_components(root)
+ return root
+
+
+def _within_root(candidate: Path, root: Path) -> None:
+ try:
+ candidate.relative_to(root)
+ except ValueError as exc:
+ raise CliError("path escapes the declared root directory") from exc
+
+
+def _suffix_matches(path: Path, suffixes: Iterable[str]) -> bool:
+ lowered = path.name.lower()
+ return any(lowered.endswith(suffix.lower()) for suffix in suffixes)
+
+
+def checked_input_file(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str],
+ max_bytes: int,
+) -> Path:
+ """Return a bounded regular local file within root, rejecting symlinks."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ root_path = checked_root(root)
+ path = Path(raw).expanduser()
+ if not path.is_absolute():
+ path = root_path / path
+ path = _absolute_lexical(path)
+ if path.is_symlink():
+ raise CliError(f"input must not be a symlink: {path.name!r}")
+ try:
+ resolved = path.resolve(strict=True)
+ info = resolved.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access input file {path.name!r}: {exc}") from exc
+ _within_root(resolved, root_path)
+ _reject_symlink_components(resolved)
+ if not stat.S_ISREG(info.st_mode):
+ raise CliError(f"input is not a regular file: {path.name!r}")
+ if info.st_size > max_bytes:
+ raise CliError(
+ f"input {path.name!r} is {info.st_size} bytes; limit is {max_bytes}"
+ )
+ if not _suffix_matches(resolved, suffixes):
+ allowed = ", ".join(sorted({suffix.lower() for suffix in suffixes}))
+ raise CliError(f"input suffix must be one of: {allowed}")
+ return resolved
+
+
+def checked_output_file(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str],
+ force: bool = False,
+) -> Path:
+ """Return a local output path within root without following symlinks."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ root_path = checked_root(root)
+ path = Path(raw).expanduser()
+ if not path.is_absolute():
+ path = root_path / path
+ path = _absolute_lexical(path)
+ if path.name in {"", ".", ".."}:
+ raise CliError("output must name a file")
+ if not _suffix_matches(path, suffixes):
+ allowed = ", ".join(sorted({suffix.lower() for suffix in suffixes}))
+ raise CliError(f"output suffix must be one of: {allowed}")
+ if path.is_symlink() or path.parent.is_symlink():
+ raise CliError("output and its parent must not be symlinks")
+ try:
+ parent = path.parent.resolve(strict=True)
+ parent_info = parent.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access output parent: {exc}") from exc
+ _within_root(parent, root_path)
+ _reject_symlink_components(parent)
+ if not stat.S_ISDIR(parent_info.st_mode):
+ raise CliError("output parent must be an existing directory")
+ destination = parent / path.name
+ if destination.exists():
+ if not destination.is_file():
+ raise CliError("output exists and is not a regular file")
+ if not force:
+ raise CliError(f"refusing to overwrite existing output: {path.name!r}")
+ return destination
+
+
+def atomic_write_bytes(
+ destination: str | os.PathLike[str],
+ payload: bytes,
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str],
+ force: bool = False,
+) -> Path:
+ """Atomically write a private, bounded file."""
+
+ if len(payload) > MAX_OUTPUT_BYTES:
+ raise CliError(f"output is {len(payload)} bytes; limit is {MAX_OUTPUT_BYTES}")
+ destination_path = checked_output_file(
+ destination, root=root, suffixes=suffixes, force=force
+ )
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=f".{destination_path.name}.",
+ suffix=".tmp",
+ dir=destination_path.parent,
+ )
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temporary, 0o600)
+ if destination_path.exists() and not force:
+ raise CliError(
+ f"refusing to overwrite existing output: {destination_path.name!r}"
+ )
+ os.replace(temporary, destination_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return destination_path
+
+
+def strict_json_bytes(document: Any) -> bytes:
+ """Serialize deterministic RFC-compatible JSON."""
+
+ try:
+ payload = (
+ json.dumps(
+ document,
+ indent=2,
+ sort_keys=True,
+ ensure_ascii=False,
+ allow_nan=False,
+ )
+ + "\n"
+ ).encode("utf-8")
+ except (TypeError, ValueError) as exc:
+ raise CliError(f"report is not strict JSON: {exc}") from exc
+ if len(payload) > MAX_OUTPUT_BYTES:
+ raise CliError(f"report is {len(payload)} bytes; limit is {MAX_OUTPUT_BYTES}")
+ return payload
+
+
+def emit_json(
+ document: Any,
+ *,
+ output: str | os.PathLike[str] | None = None,
+ root: str | os.PathLike[str] = ".",
+ force: bool = False,
+) -> None:
+ """Print strict JSON or atomically write it with private permissions."""
+
+ payload = strict_json_bytes(document)
+ if output is None:
+ print(payload.decode("utf-8"), end="")
+ return
+ atomic_write_bytes(
+ output,
+ payload,
+ root=root,
+ suffixes={".json"},
+ force=force,
+ )
+
+
+def load_json_object(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ max_bytes: int = MAX_JSON_BYTES,
+) -> dict[str, Any]:
+ """Load a bounded strict JSON object."""
+
+ path = checked_input_file(
+ value,
+ root=root,
+ suffixes={".json"},
+ max_bytes=max_bytes,
+ )
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ document = json.load(
+ handle,
+ parse_constant=_reject_constant,
+ object_pairs_hook=_unique_object,
+ )
+ except CliError:
+ raise
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise CliError(f"cannot read valid JSON from {path.name!r}: {exc}") from exc
+ if not isinstance(document, dict):
+ raise CliError("JSON root must be an object")
+ return document
+
+
+def validate_keys(
+ value: Mapping[str, Any],
+ *,
+ allowed: Iterable[str],
+ required: Iterable[str] = (),
+ context: str,
+) -> None:
+ allowed_set = set(allowed)
+ required_set = set(required)
+ unknown = sorted(set(value) - allowed_set)
+ missing = sorted(required_set - set(value))
+ if unknown:
+ raise CliError(f"{context} has unknown keys: {', '.join(unknown)}")
+ if missing:
+ raise CliError(f"{context} is missing keys: {', '.join(missing)}")
+
+
+def bounded_int(
+ value: Any,
+ *,
+ name: str,
+ minimum: int,
+ maximum: int,
+) -> int:
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise CliError(f"{name} must be an integer")
+ if not minimum <= value <= maximum:
+ raise CliError(f"{name} must be between {minimum} and {maximum}")
+ return value
+
+
+def finite_float(
+ value: Any,
+ *,
+ name: str,
+ minimum: float | None = None,
+ maximum: float | None = None,
+) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise CliError(f"{name} must be numeric")
+ number = float(value)
+ if not math.isfinite(number):
+ raise CliError(f"{name} must be finite")
+ if minimum is not None and number < minimum:
+ raise CliError(f"{name} must be at least {minimum}")
+ if maximum is not None and number > maximum:
+ raise CliError(f"{name} must be at most {maximum}")
+ return number
+
+
+def parse_name_list(value: str | None, *, name: str) -> list[str]:
+ if value is None:
+ return []
+ names = [item.strip() for item in value.split(",")]
+ if not names or any(not item for item in names):
+ raise CliError(f"{name} must be a comma-separated list of nonempty names")
+ if len(names) != len(set(names)):
+ raise CliError(f"{name} must not contain duplicates")
+ return names
+
+
+def require_deidentified(confirmed: bool) -> None:
+ if not confirmed:
+ raise CliError(
+ "local participant data require --deidentified; remove direct identifiers "
+ "and review quasi-identifiers before use"
+ )
+
+
+def _read_header(reader: Any) -> list[str]:
+ try:
+ header = next(reader)
+ except StopIteration as exc:
+ raise CliError("CSV is empty") from exc
+ if not header or any(not name.strip() for name in header):
+ raise CliError("CSV header names must be nonempty")
+ header = [name.strip() for name in header]
+ if len(header) != len(set(header)):
+ raise CliError("CSV header names must be unique")
+ if len(header) > MAX_CHANNELS:
+ raise CliError(f"CSV has {len(header)} columns; limit is {MAX_CHANNELS}")
+ return header
+
+
+def read_numeric_columns(
+ path: Path,
+ columns: Sequence[str],
+ *,
+ max_rows: int = MAX_ROWS,
+ allow_missing: bool = False,
+) -> tuple[dict[str, list[float | None]], list[str], int]:
+ """Read selected numeric CSV columns after bounded structural validation."""
+
+ if not 1 <= max_rows <= MAX_ROWS:
+ raise CliError(f"max_rows must be between 1 and {MAX_ROWS}")
+ if not columns or len(columns) > MAX_SELECTED_COLUMNS:
+ raise CliError(f"select between 1 and {MAX_SELECTED_COLUMNS} numeric columns")
+ if len(columns) != len(set(columns)):
+ raise CliError("selected columns must be unique")
+ selected: dict[str, list[float | None]] = {name: [] for name in columns}
+ try:
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
+ reader = csv.reader(handle)
+ header = _read_header(reader)
+ missing = [name for name in columns if name not in header]
+ if missing:
+ raise CliError(f"CSV is missing columns: {', '.join(missing)}")
+ positions = {name: header.index(name) for name in columns}
+ row_count = 0
+ for row_count, row in enumerate(reader, start=1):
+ if row_count > max_rows:
+ raise CliError(f"CSV exceeds the row limit of {max_rows}")
+ if len(row) != len(header):
+ raise CliError(
+ f"CSV row {row_count + 1} has {len(row)} cells; "
+ f"expected {len(header)}"
+ )
+ for name, position in positions.items():
+ cell = row[position].strip()
+ if len(cell) > MAX_CELL_CHARS:
+ raise CliError(
+ f"CSV cell in column {name!r} exceeds "
+ f"{MAX_CELL_CHARS} characters"
+ )
+ if cell.lower() in MISSING_TOKENS:
+ if allow_missing:
+ selected[name].append(None)
+ continue
+ raise CliError(
+ f"column {name!r} contains a missing value at data row "
+ f"{row_count}; segment or apply a documented bounded "
+ "imputation policy before processing"
+ )
+ try:
+ number = float(cell)
+ except ValueError as exc:
+ raise CliError(
+ f"column {name!r} contains non-numeric data at data row "
+ f"{row_count}"
+ ) from exc
+ if not math.isfinite(number):
+ raise CliError(
+ f"column {name!r} contains a non-finite value at data row "
+ f"{row_count}"
+ )
+ selected[name].append(number)
+ except CliError:
+ raise
+ except (OSError, UnicodeError, csv.Error) as exc:
+ raise CliError(f"cannot read bounded CSV: {exc}") from exc
+ if row_count == 0:
+ raise CliError("CSV has a header but no data rows")
+ return selected, header, row_count
+
+
+def _format_csv_value(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, bool):
+ return "1" if value else "0"
+ if isinstance(value, int):
+ return str(value)
+ if isinstance(value, float):
+ if not math.isfinite(value):
+ return ""
+ return format(value, ".12g")
+ item = getattr(value, "item", None)
+ if callable(item):
+ converted = item()
+ if converted is not value:
+ return _format_csv_value(converted)
+ text = str(value)
+ if len(text) > MAX_CELL_CHARS:
+ raise CliError("output CSV cell is too large")
+ return text
+
+
+def csv_bytes(columns: Sequence[str], rows: Iterable[Sequence[Any]]) -> bytes:
+ """Serialize a deterministic UTF-8 CSV with Unix newlines."""
+
+ if not columns or len(columns) > MAX_CHANNELS:
+ raise CliError(f"CSV output must have 1 to {MAX_CHANNELS} columns")
+ if len(columns) != len(set(columns)):
+ raise CliError("CSV output columns must be unique")
+ buffer = io.StringIO(newline="")
+ writer = csv.writer(buffer, lineterminator="\n")
+ writer.writerow(columns)
+ count = 0
+ for count, row in enumerate(rows, start=1):
+ if count > MAX_ROWS:
+ raise CliError(f"CSV output exceeds the row limit of {MAX_ROWS}")
+ values = list(row)
+ if len(values) != len(columns):
+ raise CliError("CSV output row length does not match columns")
+ writer.writerow([_format_csv_value(value) for value in values])
+ if buffer.tell() > MAX_OUTPUT_BYTES:
+ raise CliError(f"CSV output exceeds {MAX_OUTPUT_BYTES} bytes")
+ if count == 0:
+ raise CliError("refusing to write a CSV without data rows")
+ payload = buffer.getvalue().encode("utf-8")
+ if len(payload) > MAX_OUTPUT_BYTES:
+ raise CliError(f"CSV output exceeds {MAX_OUTPUT_BYTES} bytes")
+ return payload
+
+
+def write_csv(
+ destination: str | os.PathLike[str],
+ columns: Sequence[str],
+ rows: Iterable[Sequence[Any]],
+ *,
+ root: str | os.PathLike[str] = ".",
+ force: bool = False,
+) -> bytes:
+ payload = csv_bytes(columns, rows)
+ atomic_write_bytes(
+ destination,
+ payload,
+ root=root,
+ suffixes={".csv"},
+ force=force,
+ )
+ return payload
+
+
+def sha256_bytes(payload: bytes) -> str:
+ return hashlib.sha256(payload).hexdigest()
+
+
+def json_number(value: Any) -> float | int | None:
+ """Return a finite JSON scalar from Python or NumPy numeric input."""
+
+ item = getattr(value, "item", None)
+ if callable(item):
+ value = item()
+ if isinstance(value, bool):
+ return int(value)
+ if isinstance(value, int):
+ return value
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return None
+ return number if math.isfinite(number) else None
+
+
+def dataframe_rows(frame: Any) -> Iterable[Sequence[Any]]:
+ """Yield rows without importing pandas at module import time."""
+
+ return frame.itertuples(index=False, name=None)
+
+
+def run_cli(function: Any) -> int:
+ """Run a CLI body with concise expected-error handling."""
+
+ try:
+ function()
+ except CliError as exc:
+ print(f"error: {exc}", file=os.sys.stderr)
+ return 2
+ except ModuleNotFoundError as exc:
+ package = exc.name or "a required package"
+ print(
+ f"error: missing dependency {package!r}; install the pinned environment "
+ f"with: {PINNED_INSTALL}",
+ file=os.sys.stderr,
+ )
+ return 2
+ except ImportError as exc:
+ print(f"error: optional dependency unavailable: {exc}", file=os.sys.stderr)
+ return 2
+ except KeyboardInterrupt:
+ print("error: interrupted", file=os.sys.stderr)
+ return 130
+ return 0
diff --git a/skills/neurokit2/scripts/ecg_hrv_pipeline.py b/skills/neurokit2/scripts/ecg_hrv_pipeline.py
new file mode 100644
index 00000000..ee53c825
--- /dev/null
+++ b/skills/neurokit2/scripts/ecg_hrv_pipeline.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""Run a bounded ECG processing and duration-aware HRV workflow."""
+
+from __future__ import annotations
+
+import argparse
+from typing import Any
+
+from _common import (
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ NEUROKIT2_VERSION,
+ PINNED_INSTALL,
+ CliError,
+ checked_input_file,
+ dataframe_rows,
+ emit_json,
+ finite_float,
+ json_number,
+ parse_name_list,
+ read_numeric_columns,
+ require_deidentified,
+ run_cli,
+ sha256_bytes,
+ write_csv,
+)
+
+ECG_METHODS = (
+ "neurokit",
+ "pantompkins1985",
+ "hamilton2002",
+ "elgendi2010",
+ "engzeemod2012",
+)
+HRV_DOMAINS = {"time", "frequency", "nonlinear"}
+
+
+def _row_to_json(frame: Any) -> dict[str, float | int | None]:
+ if len(frame) != 1:
+ raise CliError("expected one-row HRV output")
+ return {str(column): json_number(frame.iloc[0][column]) for column in frame.columns}
+
+
+def _summary(values: Any) -> dict[str, float | int | None]:
+ finite = values[values.notna()] if hasattr(values, "notna") else values
+ if len(finite) == 0:
+ return {"count": 0, "maximum": None, "mean": None, "minimum": None}
+ return {
+ "count": len(finite),
+ "maximum": json_number(finite.max()),
+ "mean": json_number(finite.mean()),
+ "minimum": json_number(finite.min()),
+ }
+
+
+def _artifact_counts(info: dict[str, Any]) -> dict[str, int]:
+ result: dict[str, int] = {}
+ for name in ("ectopic", "missed", "extra", "longshort"):
+ value = info.get(f"ECG_fixpeaks_{name}", [])
+ try:
+ result[name] = len(value)
+ except TypeError:
+ result[name] = 0
+ return result
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Process a bounded deidentified ECG CSV or a reproducible synthetic "
+ "signal with NeuroKit2 0.2.13, report peak correction and quality, "
+ "and gate HRV domains by duration and beat count."
+ )
+ )
+ source = parser.add_mutually_exclusive_group(required=True)
+ source.add_argument("--input", help="local .csv input")
+ source.add_argument("--synthetic", action="store_true")
+ parser.add_argument("--column", default="ECG")
+ parser.add_argument("--sampling-rate", type=float, required=True, help="Hz")
+ parser.add_argument("--method", choices=ECG_METHODS, default="neurokit")
+ parser.add_argument(
+ "--domains",
+ default="time",
+ help="comma-separated subset of time,frequency,nonlinear",
+ )
+ parser.add_argument(
+ "--duration", type=float, default=60.0, help="synthetic seconds"
+ )
+ parser.add_argument("--heart-rate", type=float, default=70.0, help="synthetic BPM")
+ parser.add_argument("--seed", type=int, default=42)
+ parser.add_argument("--root", default=".")
+ parser.add_argument("--max-rows", type=int, default=MAX_ROWS)
+ parser.add_argument(
+ "--deidentified",
+ action="store_true",
+ help="required with --input",
+ )
+ parser.add_argument("--signals-output", help="optional processed local .csv")
+ parser.add_argument("--output", help="optional local .json report")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ sampling_rate = finite_float(
+ args.sampling_rate,
+ name="--sampling-rate",
+ minimum=20.0,
+ maximum=20_000.0,
+ )
+ domains = set(parse_name_list(args.domains, name="--domains"))
+ unknown = sorted(domains - HRV_DOMAINS)
+ if unknown:
+ raise CliError(f"unknown HRV domains: {', '.join(unknown)}")
+ if not domains:
+ raise CliError("select at least one HRV domain")
+ if not 1 <= args.max_rows <= MAX_ROWS:
+ raise CliError(f"--max-rows must be between 1 and {MAX_ROWS}")
+ if not -(2**31) <= args.seed < 2**31:
+ raise CliError("--seed must be a signed 32-bit integer")
+
+ import neurokit2 as nk
+ import numpy as np
+
+ installed = str(nk.__version__)
+ if installed != NEUROKIT2_VERSION:
+ raise CliError(
+ f"this reproducible workflow requires NeuroKit2 {NEUROKIT2_VERSION}; "
+ f"found {installed}. Install with: {PINNED_INSTALL}"
+ )
+
+ if args.input:
+ require_deidentified(args.deidentified)
+ path = checked_input_file(
+ args.input,
+ root=args.root,
+ suffixes={".csv"},
+ max_bytes=MAX_CSV_BYTES,
+ )
+ selected, _, row_count = read_numeric_columns(
+ path,
+ [args.column],
+ max_rows=args.max_rows,
+ )
+ ecg = np.asarray(selected[args.column], dtype=float)
+ source = "deidentified_local_csv"
+ else:
+ duration = finite_float(
+ args.duration,
+ name="--duration",
+ minimum=5.0,
+ maximum=3600.0,
+ )
+ heart_rate = finite_float(
+ args.heart_rate,
+ name="--heart-rate",
+ minimum=20.0,
+ maximum=240.0,
+ )
+ if not sampling_rate.is_integer():
+ raise CliError(
+ "--sampling-rate must be an integer for NeuroKit2 synthetic ECG"
+ )
+ row_count = round(duration * sampling_rate)
+ if not 1 <= row_count <= args.max_rows:
+ raise CliError(f"synthetic row count must be between 1 and {args.max_rows}")
+ try:
+ ecg = nk.ecg_simulate(
+ duration=duration,
+ sampling_rate=int(sampling_rate),
+ heart_rate=heart_rate,
+ random_state=args.seed,
+ )
+ except (TypeError, ValueError, RuntimeError) as exc:
+ raise CliError(f"synthetic ECG generation failed: {exc}") from exc
+ row_count = len(ecg)
+ source = "neurokit2_synthetic"
+
+ duration_s = len(ecg) / sampling_rate
+ if duration_s < 5:
+ raise CliError("ECG must contain at least 5 seconds for this pipeline")
+ try:
+ signals, info = nk.ecg_process(
+ ecg,
+ sampling_rate=sampling_rate,
+ method=args.method,
+ )
+ except (TypeError, ValueError, RuntimeError, IndexError) as exc:
+ raise CliError(f"ECG processing failed: {exc}") from exc
+ peaks = info.get("ECG_R_Peaks")
+ if peaks is None or len(peaks) < 3:
+ raise CliError("fewer than three R-peaks were detected")
+ beat_count = len(peaks)
+
+ warnings: list[str] = []
+ hrv: dict[str, dict[str, float | int | None]] = {}
+ if "time" in domains:
+ if beat_count < 20:
+ warnings.append("time-domain HRV skipped: fewer than 20 detected beats")
+ else:
+ try:
+ hrv["time"] = _row_to_json(
+ nk.hrv_time(info, sampling_rate=sampling_rate)
+ )
+ except (TypeError, ValueError, RuntimeError, ZeroDivisionError) as exc:
+ warnings.append(f"time-domain HRV failed: {exc}")
+ if duration_s < 300:
+ warnings.append(
+ "time-domain HRV is shorter than the conventional 5-minute "
+ "short-term recording; metric-specific validation is required"
+ )
+ if "frequency" in domains:
+ if duration_s < 120 or beat_count < 50:
+ warnings.append(
+ "frequency-domain HRV skipped: require at least 120 seconds and "
+ "50 detected beats in this conservative CLI"
+ )
+ else:
+ try:
+ hrv["frequency"] = _row_to_json(
+ nk.hrv_frequency(info, sampling_rate=sampling_rate)
+ )
+ except (TypeError, ValueError, RuntimeError, ZeroDivisionError) as exc:
+ warnings.append(f"frequency-domain HRV failed: {exc}")
+ if duration_s < 300:
+ warnings.append(
+ "frequency-domain HRV is below the conventional 5-minute "
+ "short-term window; do not interpret VLF/ULF and justify bands"
+ )
+ if "nonlinear" in domains:
+ if beat_count < 100:
+ warnings.append(
+ "nonlinear HRV skipped: fewer than 100 detected beats; many "
+ "entropy/fractal metrics need substantially more"
+ )
+ else:
+ try:
+ hrv["nonlinear"] = _row_to_json(
+ nk.hrv_nonlinear(info, sampling_rate=sampling_rate)
+ )
+ except (TypeError, ValueError, RuntimeError, ZeroDivisionError) as exc:
+ warnings.append(f"nonlinear HRV failed: {exc}")
+
+ artifact_counts = _artifact_counts(info)
+ corrected_total = sum(artifact_counts.values())
+ if corrected_total:
+ warnings.append(
+ "R-peak corrections were applied by ecg_process(); inspect the raw "
+ "trace, uncorrected peaks, and correction categories"
+ )
+ if source == "deidentified_local_csv":
+ warnings.append(
+ "input amplitude units are not inferred; record sensor units, lead, "
+ "gain, filters, and clock metadata separately"
+ )
+
+ report: dict[str, Any] = {
+ "artifact_correction": {
+ "algorithm": "Lipponen-Tarvainen via ecg_process(correct_artifacts=True)",
+ "category_counts": artifact_counts,
+ "corrected_event_count_sum": corrected_total,
+ "uncorrected_peak_count": len(info.get("ECG_R_Peaks_Uncorrected", peaks)),
+ },
+ "detected_r_peaks": beat_count,
+ "duration_s": duration_s,
+ "hrv": hrv,
+ "hrv_requested_domains": sorted(domains),
+ "neurokit2_version": installed,
+ "output_schema_observed": {
+ "info_keys": sorted(str(key) for key in info),
+ "signal_columns": [str(column) for column in signals.columns],
+ },
+ "path_redacted": True,
+ "quality": _summary(signals["ECG_Quality"]),
+ "research_use_only": True,
+ "row_count": row_count,
+ "sampling_rate_hz": sampling_rate,
+ "source": source,
+ "warning": (
+ "This output is for research and education, not diagnosis, patient "
+ "monitoring, or medical-device validation. Validate the detector, "
+ "sensor, population, protocol, and artifact policy for the intended use."
+ ),
+ "warnings": warnings,
+ }
+ if args.signals_output:
+ payload = write_csv(
+ args.signals_output,
+ [str(column) for column in signals.columns],
+ dataframe_rows(signals),
+ root=args.root,
+ force=args.force,
+ )
+ report["signals_csv"] = {
+ "path_redacted": True,
+ "sha256": sha256_bytes(payload),
+ }
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/scripts/eda_pipeline.py b/skills/neurokit2/scripts/eda_pipeline.py
new file mode 100644
index 00000000..50f65cfe
--- /dev/null
+++ b/skills/neurokit2/scripts/eda_pipeline.py
@@ -0,0 +1,288 @@
+#!/usr/bin/env python3
+"""Run an explicit, bounded EDA cleaning/decomposition/SCR workflow."""
+
+from __future__ import annotations
+
+import argparse
+import statistics
+from typing import Any
+
+from _common import (
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ NEUROKIT2_VERSION,
+ PINNED_INSTALL,
+ CliError,
+ checked_input_file,
+ dataframe_rows,
+ emit_json,
+ finite_float,
+ json_number,
+ read_numeric_columns,
+ require_deidentified,
+ run_cli,
+ sha256_bytes,
+ write_csv,
+)
+
+CLEAN_METHODS = ("neurokit", "biosppy", "none")
+PHASIC_METHODS = ("highpass", "smoothmedian", "cvxeda", "sparseda")
+PEAK_METHODS = ("neurokit", "gamboa2008", "kim2004", "vanhalem2020", "nabian2018")
+
+
+def _finite_values(values: Any) -> list[float]:
+ result: list[float] = []
+ for value in values:
+ number = json_number(value)
+ if number is not None:
+ result.append(float(number))
+ return result
+
+
+def _stats(values: Any) -> dict[str, float | int | None]:
+ finite = _finite_values(values)
+ return {
+ "count": len(finite),
+ "maximum": max(finite) if finite else None,
+ "mean": statistics.fmean(finite) if finite else None,
+ "median": statistics.median(finite) if finite else None,
+ "minimum": min(finite) if finite else None,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Clean, explicitly decompose, and detect SCRs in bounded "
+ "deidentified EDA CSV data or a reproducible synthetic signal using "
+ "NeuroKit2 0.2.13."
+ )
+ )
+ source = parser.add_mutually_exclusive_group(required=True)
+ source.add_argument("--input", help="local .csv input")
+ source.add_argument("--synthetic", action="store_true")
+ parser.add_argument("--column", default="EDA")
+ parser.add_argument("--sampling-rate", type=float, required=True, help="Hz")
+ parser.add_argument("--clean-method", choices=CLEAN_METHODS, default="neurokit")
+ parser.add_argument("--phasic-method", choices=PHASIC_METHODS, default="highpass")
+ parser.add_argument("--peak-method", choices=PEAK_METHODS, default="neurokit")
+ parser.add_argument(
+ "--amplitude-min",
+ type=float,
+ default=0.1,
+ help="relative-to-largest SCR threshold for neurokit/kim2004",
+ )
+ parser.add_argument(
+ "--sympathetic-method",
+ choices=("none", "posada", "ghiasi"),
+ default="none",
+ )
+ parser.add_argument("--unit", default="unspecified")
+ parser.add_argument(
+ "--duration", type=float, default=60.0, help="synthetic seconds"
+ )
+ parser.add_argument("--scr-number", type=int, default=6)
+ parser.add_argument("--seed", type=int, default=42)
+ parser.add_argument("--root", default=".")
+ parser.add_argument("--max-rows", type=int, default=MAX_ROWS)
+ parser.add_argument(
+ "--deidentified",
+ action="store_true",
+ help="required with --input",
+ )
+ parser.add_argument("--signals-output", help="optional processed local .csv")
+ parser.add_argument("--output", help="optional local .json report")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ sampling_rate = finite_float(
+ args.sampling_rate,
+ name="--sampling-rate",
+ minimum=1.0,
+ maximum=5000.0,
+ )
+ amplitude_min = finite_float(
+ args.amplitude_min,
+ name="--amplitude-min",
+ minimum=0.0,
+ maximum=1.0,
+ )
+ if not 1 <= args.max_rows <= MAX_ROWS:
+ raise CliError(f"--max-rows must be between 1 and {MAX_ROWS}")
+ if not 0 <= args.scr_number <= 10_000:
+ raise CliError("--scr-number must be between 0 and 10000")
+ if not -(2**31) <= args.seed < 2**31:
+ raise CliError("--seed must be a signed 32-bit integer")
+ if not args.unit or len(args.unit) > 32:
+ raise CliError("--unit must be a nonempty string of at most 32 characters")
+
+ import neurokit2 as nk
+ import numpy as np
+ import pandas as pd
+
+ installed = str(nk.__version__)
+ if installed != NEUROKIT2_VERSION:
+ raise CliError(
+ f"this reproducible workflow requires NeuroKit2 {NEUROKIT2_VERSION}; "
+ f"found {installed}. Install with: {PINNED_INSTALL}"
+ )
+
+ if args.input:
+ require_deidentified(args.deidentified)
+ path = checked_input_file(
+ args.input,
+ root=args.root,
+ suffixes={".csv"},
+ max_bytes=MAX_CSV_BYTES,
+ )
+ selected, _, row_count = read_numeric_columns(
+ path,
+ [args.column],
+ max_rows=args.max_rows,
+ )
+ raw = np.asarray(selected[args.column], dtype=float)
+ source = "deidentified_local_csv"
+ else:
+ duration = finite_float(
+ args.duration,
+ name="--duration",
+ minimum=5.0,
+ maximum=3600.0,
+ )
+ if not sampling_rate.is_integer():
+ raise CliError(
+ "--sampling-rate must be an integer for NeuroKit2 synthetic EDA"
+ )
+ row_count = round(duration * sampling_rate)
+ if not 1 <= row_count <= args.max_rows:
+ raise CliError(f"synthetic row count must be between 1 and {args.max_rows}")
+ try:
+ raw = nk.eda_simulate(
+ length=row_count,
+ sampling_rate=int(sampling_rate),
+ scr_number=args.scr_number,
+ random_state=args.seed,
+ )
+ except (TypeError, ValueError, RuntimeError) as exc:
+ raise CliError(f"synthetic EDA generation failed: {exc}") from exc
+ row_count = len(raw)
+ source = "neurokit2_synthetic"
+
+ duration_s = len(raw) / sampling_rate
+ try:
+ clean = nk.eda_clean(
+ raw,
+ sampling_rate=sampling_rate,
+ method=args.clean_method,
+ )
+ components = nk.eda_phasic(
+ clean,
+ sampling_rate=sampling_rate,
+ method=args.phasic_method,
+ )
+ peak_signals, peak_info = nk.eda_peaks(
+ components["EDA_Phasic"],
+ sampling_rate=sampling_rate,
+ method=args.peak_method,
+ amplitude_min=amplitude_min,
+ )
+ except (TypeError, ValueError, RuntimeError, IndexError) as exc:
+ raise CliError(f"EDA processing failed: {exc}") from exc
+
+ signals = pd.concat(
+ [
+ pd.DataFrame({"EDA_Raw": raw, "EDA_Clean": clean}),
+ components.reset_index(drop=True),
+ peak_signals.reset_index(drop=True),
+ ],
+ axis=1,
+ )
+ amplitudes = _finite_values(peak_info.get("SCR_Amplitude", []))
+ scr_count = len(peak_info.get("SCR_Peaks", []))
+ warnings: list[str] = []
+ if args.phasic_method == "cvxeda":
+ warnings.append(
+ "cvxEDA requires the optional cvxopt dependency; report its version "
+ "and validate decomposition parameters"
+ )
+ if source == "deidentified_local_csv" and args.unit == "unspecified":
+ warnings.append(
+ "EDA units were not declared; do not interpret amplitudes as "
+ "microsiemens without acquisition metadata"
+ )
+ if scr_count == 0:
+ warnings.append(
+ "no SCR peaks were detected; inspect signal orientation and quality"
+ )
+ sympathetic: dict[str, float | int | None] | None = None
+ if args.sympathetic_method != "none":
+ if duration_s < 64:
+ warnings.append(
+ "EDA sympathetic index skipped: this CLI requires at least 64 seconds"
+ )
+ else:
+ try:
+ result = nk.eda_sympathetic(
+ clean,
+ sampling_rate=sampling_rate,
+ method=args.sympathetic_method,
+ show=False,
+ )
+ sympathetic = {
+ str(key): json_number(value) for key, value in result.items()
+ }
+ except (TypeError, ValueError, RuntimeError, ZeroDivisionError) as exc:
+ warnings.append(f"EDA sympathetic index failed: {exc}")
+
+ report: dict[str, Any] = {
+ "duration_s": duration_s,
+ "input_unit": args.unit,
+ "methods": {
+ "clean": args.clean_method,
+ "decomposition": args.phasic_method,
+ "peak_detection": args.peak_method,
+ "peak_threshold_relative_to_largest": amplitude_min,
+ "sympathetic": args.sympathetic_method,
+ },
+ "neurokit2_version": installed,
+ "output_schema_observed": {
+ "info_keys": sorted(str(key) for key in peak_info),
+ "signal_columns": [str(column) for column in signals.columns],
+ },
+ "path_redacted": True,
+ "research_use_only": True,
+ "row_count": row_count,
+ "sampling_rate_hz": sampling_rate,
+ "scr": {
+ "amplitude": _stats(amplitudes),
+ "count": scr_count,
+ },
+ "source": source,
+ "sympathetic": sympathetic,
+ "tonic": _stats(signals["EDA_Tonic"]),
+ "warning": (
+ "EDA features are method-, sensor-, site-, unit-, and population-dependent. "
+ "This output is not diagnosis, monitoring, or medical-device validation."
+ ),
+ "warnings": warnings,
+ }
+ if args.signals_output:
+ payload = write_csv(
+ args.signals_output,
+ [str(column) for column in signals.columns],
+ dataframe_rows(signals),
+ root=args.root,
+ force=args.force,
+ )
+ report["signals_csv"] = {
+ "path_redacted": True,
+ "sha256": sha256_bytes(payload),
+ }
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/scripts/generate_synthetic.py b/skills/neurokit2/scripts/generate_synthetic.py
new file mode 100644
index 00000000..75676f2f
--- /dev/null
+++ b/skills/neurokit2/scripts/generate_synthetic.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python3
+"""Generate deterministic, dependency-free synthetic biosignal CSV fixtures."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import random
+from collections.abc import Sequence
+from typing import Any
+
+from _common import (
+ MAX_ROWS,
+ CliError,
+ emit_json,
+ finite_float,
+ parse_name_list,
+ run_cli,
+ sha256_bytes,
+ write_csv,
+)
+
+MODALITIES = ("ecg", "ppg", "rsp", "eda", "emg", "trigger")
+UNITS = {
+ "time_s": "s",
+ "ecg": "arbitrary_unit",
+ "ppg": "arbitrary_unit",
+ "rsp": "arbitrary_unit",
+ "eda": "arbitrary_unit",
+ "emg": "arbitrary_unit",
+ "trigger": "binary",
+}
+
+
+def _gaussian(phase: float, center: float, width: float) -> float:
+ distance = min(abs(phase - center), 1.0 - abs(phase - center))
+ return math.exp(-0.5 * (distance / width) ** 2)
+
+
+def _event_times(duration: float, interval: float) -> list[float]:
+ first = interval
+ return [
+ first + index * interval
+ for index in range(max(0, int((duration - first) // interval) + 1))
+ if first + index * interval < duration
+ ]
+
+
+def generate_rows(
+ *,
+ duration: float,
+ sampling_rate: float,
+ heart_rate: float,
+ respiratory_rate: float,
+ modalities: Sequence[str],
+ seed: int,
+ event_interval: float,
+) -> tuple[list[str], list[list[float]], list[float]]:
+ """Return deterministic analytic fixtures, not validated physiology."""
+
+ samples = round(duration * sampling_rate)
+ if not 1 <= samples <= MAX_ROWS:
+ raise CliError(f"synthetic row count must be between 1 and {MAX_ROWS}")
+ rng = random.Random(seed)
+ events = _event_times(duration, event_interval)
+ cardiac_period = 60.0 / heart_rate
+ respiratory_period = 60.0 / respiratory_rate
+ columns = ["time_s", *modalities]
+ rows: list[list[float]] = []
+
+ for sample in range(samples):
+ time_s = sample / sampling_rate
+ cardiac_phase = (time_s % cardiac_period) / cardiac_period
+ respiratory_phase = (time_s % respiratory_period) / respiratory_period
+ values: dict[str, float] = {}
+
+ if "ecg" in modalities:
+ values["ecg"] = (
+ 0.12 * _gaussian(cardiac_phase, 0.18, 0.025)
+ - 0.15 * _gaussian(cardiac_phase, 0.36, 0.012)
+ + 1.00 * _gaussian(cardiac_phase, 0.40, 0.010)
+ - 0.25 * _gaussian(cardiac_phase, 0.43, 0.014)
+ + 0.30 * _gaussian(cardiac_phase, 0.68, 0.055)
+ + rng.gauss(0.0, 0.008)
+ )
+ if "ppg" in modalities:
+ pulse = max(0.0, math.sin(math.pi * cardiac_phase)) ** 2.5
+ notch = 0.12 * _gaussian(cardiac_phase, 0.72, 0.035)
+ values["ppg"] = pulse - notch + rng.gauss(0.0, 0.006)
+ if "rsp" in modalities:
+ values["rsp"] = math.sin(2 * math.pi * respiratory_phase) + rng.gauss(
+ 0.0, 0.01
+ )
+ if "eda" in modalities:
+ phasic = 0.0
+ for event_time in events:
+ elapsed = time_s - event_time
+ if elapsed >= 0:
+ phasic += (1.0 - math.exp(-elapsed / 0.45)) * math.exp(
+ -elapsed / 2.2
+ )
+ values["eda"] = (
+ 1.0 + 0.002 * time_s + 0.15 * phasic + rng.gauss(0.0, 0.0015)
+ )
+ if "emg" in modalities:
+ active = any(0.5 <= time_s - event_time < 1.2 for event_time in events)
+ scale = 0.16 if active else 0.01
+ values["emg"] = rng.gauss(0.0, scale)
+ if "trigger" in modalities:
+ values["trigger"] = (
+ 1.0
+ if any(
+ 0 <= time_s - event_time < max(0.02, 2.0 / sampling_rate)
+ for event_time in events
+ )
+ else 0.0
+ )
+ rows.append([time_s, *(values[name] for name in modalities)])
+ return columns, rows, events
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Generate a deterministic local CSV of analytic biosignal-like fixtures. "
+ "The output is for software tests and education, not physiological validation."
+ )
+ )
+ parser.add_argument("--output", required=True, help="local .csv output path")
+ parser.add_argument("--root", default=".", help="existing local I/O boundary")
+ parser.add_argument("--duration", type=float, default=30.0, help="seconds")
+ parser.add_argument("--sampling-rate", type=float, default=250.0, help="Hz")
+ parser.add_argument("--heart-rate", type=float, default=70.0, help="beats/min")
+ parser.add_argument(
+ "--respiratory-rate", type=float, default=15.0, help="breaths/min"
+ )
+ parser.add_argument(
+ "--modalities",
+ default="ecg,rsp,eda,trigger",
+ help=f"comma-separated subset of: {', '.join(MODALITIES)}",
+ )
+ parser.add_argument("--event-interval", type=float, default=5.0, help="seconds")
+ parser.add_argument("--seed", type=int, default=42)
+ parser.add_argument("--report", help="optional local .json report path")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ duration = finite_float(
+ args.duration, name="--duration", minimum=0.1, maximum=3600.0
+ )
+ sampling_rate = finite_float(
+ args.sampling_rate,
+ name="--sampling-rate",
+ minimum=1.0,
+ maximum=5000.0,
+ )
+ heart_rate = finite_float(
+ args.heart_rate, name="--heart-rate", minimum=20.0, maximum=240.0
+ )
+ respiratory_rate = finite_float(
+ args.respiratory_rate,
+ name="--respiratory-rate",
+ minimum=2.0,
+ maximum=80.0,
+ )
+ event_interval = finite_float(
+ args.event_interval,
+ name="--event-interval",
+ minimum=0.5,
+ maximum=3600.0,
+ )
+ modalities = parse_name_list(args.modalities, name="--modalities")
+ unknown = sorted(set(modalities) - set(MODALITIES))
+ if unknown:
+ raise CliError(f"unknown modalities: {', '.join(unknown)}")
+ if not modalities:
+ raise CliError("select at least one modality")
+ if not -(2**31) <= args.seed < 2**31:
+ raise CliError("--seed must be a signed 32-bit integer")
+
+ columns, rows, event_times = generate_rows(
+ duration=duration,
+ sampling_rate=sampling_rate,
+ heart_rate=heart_rate,
+ respiratory_rate=respiratory_rate,
+ modalities=modalities,
+ seed=args.seed,
+ event_interval=event_interval,
+ )
+ payload = write_csv(
+ args.output,
+ columns,
+ rows,
+ root=args.root,
+ force=args.force,
+ )
+ report: dict[str, Any] = {
+ "artifact": "synthetic_biosignal_fixture",
+ "columns": columns,
+ "duration_s": duration,
+ "event_onsets_s": event_times,
+ "path_redacted": True,
+ "physiological_validation": False,
+ "row_count": len(rows),
+ "sampling_rate_hz": sampling_rate,
+ "seed": args.seed,
+ "sha256": sha256_bytes(payload),
+ "units": {column: UNITS[column] for column in columns},
+ "warning": (
+ "Analytic waveforms are deterministic software fixtures; they do not "
+ "validate a sensor, method, population, diagnosis, or medical device."
+ ),
+ }
+ emit_json(report, output=args.report, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/scripts/inspect_signal.py b/skills/neurokit2/scripts/inspect_signal.py
new file mode 100644
index 00000000..0ce22e1e
--- /dev/null
+++ b/skills/neurokit2/scripts/inspect_signal.py
@@ -0,0 +1,362 @@
+#!/usr/bin/env python3
+"""Inspect bounded local biosignal CSV structure without exposing row values."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import math
+import statistics
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ MAX_CELL_CHARS,
+ MAX_CHANNELS,
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ MISSING_TOKENS,
+ CliError,
+ checked_input_file,
+ emit_json,
+ finite_float,
+ parse_name_list,
+ require_deidentified,
+ run_cli,
+)
+
+
+class OnlineStats:
+ def __init__(self) -> None:
+ self.numeric = 0
+ self.missing = 0
+ self.nonfinite = 0
+ self.nonnumeric = 0
+ self.mean = 0.0
+ self.m2 = 0.0
+ self.minimum = math.inf
+ self.maximum = -math.inf
+ self.previous: float | None = None
+ self.transitions = 0
+ self.flat_transitions = 0
+ self.flat_run = 0
+ self.max_flat_run = 0
+ self.gap_run = 0
+ self.max_gap_run = 0
+
+ def add_cell(self, cell: str) -> float | None:
+ normalized = cell.strip()
+ if normalized.lower() in MISSING_TOKENS:
+ self.missing += 1
+ self.gap_run += 1
+ self.max_gap_run = max(self.max_gap_run, self.gap_run)
+ self.previous = None
+ self.flat_run = 0
+ return None
+ try:
+ value = float(normalized)
+ except ValueError:
+ self.nonnumeric += 1
+ self.gap_run += 1
+ self.max_gap_run = max(self.max_gap_run, self.gap_run)
+ self.previous = None
+ self.flat_run = 0
+ return None
+ if not math.isfinite(value):
+ self.nonfinite += 1
+ self.gap_run += 1
+ self.max_gap_run = max(self.max_gap_run, self.gap_run)
+ self.previous = None
+ self.flat_run = 0
+ return None
+
+ self.gap_run = 0
+ self.numeric += 1
+ delta = value - self.mean
+ self.mean += delta / self.numeric
+ self.m2 += delta * (value - self.mean)
+ self.minimum = min(self.minimum, value)
+ self.maximum = max(self.maximum, value)
+ if self.previous is not None:
+ self.transitions += 1
+ if value == self.previous:
+ self.flat_transitions += 1
+ self.flat_run += 1
+ else:
+ self.flat_run = 0
+ self.max_flat_run = max(self.max_flat_run, self.flat_run)
+ self.previous = value
+ return value
+
+ def report(self, unit: str | None) -> dict[str, Any]:
+ variance = self.m2 / (self.numeric - 1) if self.numeric > 1 else None
+ return {
+ "flat_transition_fraction": (
+ self.flat_transitions / self.transitions if self.transitions else None
+ ),
+ "maximum": self.maximum if self.numeric else None,
+ "max_flat_run_samples": self.max_flat_run + 1 if self.max_flat_run else 0,
+ "max_gap_run_samples": self.max_gap_run,
+ "mean": self.mean if self.numeric else None,
+ "minimum": self.minimum if self.numeric else None,
+ "missing_count": self.missing,
+ "nonfinite_count": self.nonfinite,
+ "nonnumeric_count": self.nonnumeric,
+ "numeric_count": self.numeric,
+ "sample_sd": math.sqrt(variance) if variance is not None else None,
+ "unit": unit or "unspecified",
+ }
+
+
+def _parse_units(value: str | None, selected: list[str]) -> dict[str, str]:
+ if value is None:
+ return {}
+ result: dict[str, str] = {}
+ for item in value.split(","):
+ if "=" not in item:
+ raise CliError("--units entries must use COLUMN=UNIT")
+ column, unit = (part.strip() for part in item.split("=", 1))
+ if not column or not unit:
+ raise CliError("--units entries must have nonempty column and unit")
+ if column in result:
+ raise CliError(f"duplicate unit declaration for {column!r}")
+ if column not in selected:
+ raise CliError(f"unit declared for unselected column {column!r}")
+ if len(unit) > 32 or any(ord(character) < 32 for character in unit):
+ raise CliError("units must be short printable strings")
+ result[column] = unit
+ return result
+
+
+def inspect_csv(
+ path: Path,
+ *,
+ selected_names: list[str] | None,
+ time_column: str | None,
+ declared_sampling_rate: float | None,
+ units_value: str | None,
+ max_rows: int,
+ max_channels: int,
+) -> dict[str, Any]:
+ if not 1 <= max_rows <= MAX_ROWS:
+ raise CliError(f"--max-rows must be between 1 and {MAX_ROWS}")
+ if not 1 <= max_channels <= MAX_CHANNELS:
+ raise CliError(f"--max-channels must be between 1 and {MAX_CHANNELS}")
+
+ try:
+ handle = path.open("r", encoding="utf-8-sig", newline="")
+ except (OSError, UnicodeError) as exc:
+ raise CliError(f"cannot open CSV: {exc}") from exc
+ with handle:
+ reader = csv.reader(handle)
+ try:
+ header = [name.strip() for name in next(reader)]
+ except StopIteration as exc:
+ raise CliError("CSV is empty") from exc
+ if not header or any(not name for name in header):
+ raise CliError("CSV header names must be nonempty")
+ if len(header) != len(set(header)):
+ raise CliError("CSV header names must be unique")
+ if len(header) > max_channels:
+ raise CliError(
+ f"CSV has {len(header)} columns; --max-channels is {max_channels}"
+ )
+ if time_column is not None and time_column not in header:
+ raise CliError(f"time column {time_column!r} is absent")
+ selected = selected_names or []
+ if not selected:
+ raise CliError("no signal columns selected")
+ if len(selected) > max_channels:
+ raise CliError(
+ f"selected {len(selected)} columns; --max-channels is {max_channels}"
+ )
+ missing = [name for name in selected if name not in header]
+ if missing:
+ raise CliError(f"CSV is missing selected columns: {', '.join(missing)}")
+ if time_column in selected:
+ raise CliError("--time-column must not also be a signal column")
+ units = _parse_units(units_value, selected)
+ positions = {name: header.index(name) for name in selected}
+ time_position = header.index(time_column) if time_column else None
+ stats = {name: OnlineStats() for name in selected}
+ time_stats = OnlineStats() if time_column else None
+ positive_deltas: list[float] = []
+ previous_time: float | None = None
+ duplicate_times = 0
+ backward_times = 0
+ row_count = 0
+
+ try:
+ for row_count, row in enumerate(reader, start=1):
+ if row_count > max_rows:
+ raise CliError(f"CSV exceeds --max-rows={max_rows}")
+ if len(row) != len(header):
+ raise CliError(
+ f"CSV row {row_count + 1} has {len(row)} cells; "
+ f"expected {len(header)}"
+ )
+ for cell in row:
+ if len(cell) > MAX_CELL_CHARS:
+ raise CliError(
+ f"CSV row {row_count + 1} contains a cell longer than "
+ f"{MAX_CELL_CHARS} characters"
+ )
+ for name, position in positions.items():
+ stats[name].add_cell(row[position])
+ if time_position is not None and time_stats is not None:
+ time_value = time_stats.add_cell(row[time_position])
+ if time_value is not None and previous_time is not None:
+ delta = time_value - previous_time
+ if delta > 0:
+ positive_deltas.append(delta)
+ elif delta == 0:
+ duplicate_times += 1
+ else:
+ backward_times += 1
+ if time_value is not None:
+ previous_time = time_value
+ except csv.Error as exc:
+ raise CliError(f"cannot parse CSV: {exc}") from exc
+
+ if row_count == 0:
+ raise CliError("CSV has a header but no data rows")
+
+ observed_sampling_rate: float | None = None
+ median_delta: float | None = None
+ maximum_relative_jitter: float | None = None
+ if positive_deltas:
+ median_delta = statistics.median(positive_deltas)
+ if median_delta > 0:
+ observed_sampling_rate = 1.0 / median_delta
+ maximum_relative_jitter = max(
+ abs(delta - median_delta) / median_delta for delta in positive_deltas
+ )
+
+ duration_s: float | None = None
+ effective_rate = observed_sampling_rate or declared_sampling_rate
+ if effective_rate and row_count > 1:
+ duration_s = (row_count - 1) / effective_rate
+
+ channel_reports = {name: stats[name].report(units.get(name)) for name in selected}
+ warnings: list[str] = []
+ for name, report in channel_reports.items():
+ invalid = (
+ report["missing_count"]
+ + report["nonfinite_count"]
+ + report["nonnumeric_count"]
+ )
+ if invalid:
+ warnings.append(
+ f"{name}: {invalid} missing, non-finite, or non-numeric samples"
+ )
+ flat_fraction = report["flat_transition_fraction"]
+ if isinstance(flat_fraction, float) and flat_fraction > 0.20:
+ warnings.append(
+ f"{name}: more than 20% of adjacent finite samples are identical"
+ )
+ if duplicate_times:
+ warnings.append("time column contains duplicate timestamps")
+ if backward_times:
+ warnings.append("time column contains backward timestamps")
+ if (
+ declared_sampling_rate
+ and observed_sampling_rate
+ and abs(observed_sampling_rate - declared_sampling_rate)
+ / declared_sampling_rate
+ > 0.01
+ ):
+ warnings.append(
+ "observed timestamp rate differs from declared sampling rate by more than 1%"
+ )
+ if maximum_relative_jitter is not None and maximum_relative_jitter > 0.01:
+ warnings.append("timestamp intervals vary by more than 1% from the median")
+
+ return {
+ "channel_count_in_file": len(header),
+ "channels": channel_reports,
+ "declared_sampling_rate_hz": declared_sampling_rate,
+ "duration_s_estimate": duration_s,
+ "observed_sampling_rate_hz": observed_sampling_rate,
+ "path_redacted": True,
+ "research_use_only": True,
+ "row_count": row_count,
+ "selected_columns": selected,
+ "time": {
+ "backward_step_count": backward_times,
+ "duplicate_count": duplicate_times,
+ "maximum_relative_interval_jitter": maximum_relative_jitter,
+ "median_interval_s": median_delta,
+ "name": time_column,
+ "stats": time_stats.report("s") if time_stats else None,
+ },
+ "warnings": warnings,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Inspect a bounded local CSV for numeric coverage, gaps, flat runs, "
+ "timestamp order, and sampling-rate consistency. Row values and paths "
+ "are never emitted."
+ )
+ )
+ parser.add_argument("--input", required=True, help="local .csv input")
+ parser.add_argument("--root", default=".", help="existing local I/O boundary")
+ parser.add_argument(
+ "--columns",
+ required=True,
+ help="explicit comma-separated signal columns",
+ )
+ parser.add_argument("--time-column", help="numeric time column in seconds")
+ parser.add_argument(
+ "--sampling-rate", type=float, help="declared sampling rate in Hz"
+ )
+ parser.add_argument(
+ "--units", help="comma-separated COLUMN=UNIT declarations, e.g. ECG=mV,EDA=uS"
+ )
+ parser.add_argument("--max-rows", type=int, default=MAX_ROWS)
+ parser.add_argument("--max-channels", type=int, default=32)
+ parser.add_argument(
+ "--deidentified",
+ action="store_true",
+ help="confirm direct and reviewed quasi-identifiers were removed",
+ )
+ parser.add_argument("--output", help="optional local .json report")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ require_deidentified(args.deidentified)
+ declared_rate = (
+ finite_float(
+ args.sampling_rate,
+ name="--sampling-rate",
+ minimum=0.01,
+ maximum=1_000_000.0,
+ )
+ if args.sampling_rate is not None
+ else None
+ )
+ path = checked_input_file(
+ args.input,
+ root=args.root,
+ suffixes={".csv"},
+ max_bytes=MAX_CSV_BYTES,
+ )
+ report = inspect_csv(
+ path,
+ selected_names=parse_name_list(args.columns, name="--columns"),
+ time_column=args.time_column,
+ declared_sampling_rate=declared_rate,
+ units_value=args.units,
+ max_rows=args.max_rows,
+ max_channels=args.max_channels,
+ )
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/scripts/plan_epochs.py b/skills/neurokit2/scripts/plan_epochs.py
new file mode 100644
index 00000000..825480e5
--- /dev/null
+++ b/skills/neurokit2/scripts/plan_epochs.py
@@ -0,0 +1,281 @@
+#!/usr/bin/env python3
+"""Plan sample-exact event epochs without loading NeuroKit2."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import Any
+
+from _common import (
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ CliError,
+ checked_input_file,
+ emit_json,
+ finite_float,
+ read_numeric_columns,
+ require_deidentified,
+ run_cli,
+)
+
+MAX_EVENTS = 100_000
+
+
+def _parse_events(value: str) -> list[float]:
+ pieces = [piece.strip() for piece in value.split(",")]
+ if not pieces or any(not piece for piece in pieces):
+ raise CliError("--events must be a comma-separated numeric list")
+ if len(pieces) > MAX_EVENTS:
+ raise CliError(f"event count exceeds {MAX_EVENTS}")
+ events: list[float] = []
+ for index, piece in enumerate(pieces, start=1):
+ try:
+ event = float(piece)
+ except ValueError as exc:
+ raise CliError(f"event {index} is not numeric") from exc
+ if not math.isfinite(event) or event < 0:
+ raise CliError(f"event {index} must be finite and nonnegative")
+ events.append(event)
+ return events
+
+
+def _sample_offset(seconds: float, sampling_rate: float, *, name: str) -> int:
+ exact = seconds * sampling_rate
+ rounded = round(exact)
+ if not math.isclose(exact, rounded, rel_tol=0.0, abs_tol=1e-8):
+ raise CliError(
+ f"{name}={seconds} s is not sample-aligned at {sampling_rate} Hz "
+ f"({exact} samples)"
+ )
+ return int(rounded)
+
+
+def _event_samples(
+ values: list[float],
+ *,
+ unit: str,
+ sampling_rate: float,
+) -> list[int]:
+ samples: list[int] = []
+ for index, value in enumerate(values, start=1):
+ if unit == "samples":
+ rounded = round(value)
+ if not math.isclose(value, rounded, rel_tol=0.0, abs_tol=1e-9):
+ raise CliError(f"event {index} is not an integer sample index: {value}")
+ sample = int(rounded)
+ else:
+ sample = _sample_offset(value, sampling_rate, name=f"event {index} onset")
+ samples.append(sample)
+ return samples
+
+
+def plan(
+ events: list[int],
+ *,
+ recording_samples: int,
+ sampling_rate: float,
+ epoch_start_s: float,
+ epoch_end_s: float,
+ baseline_start_s: float | None,
+ baseline_end_s: float | None,
+ boundary_policy: str,
+) -> dict[str, Any]:
+ start_offset = _sample_offset(epoch_start_s, sampling_rate, name="--epoch-start")
+ end_offset = _sample_offset(epoch_end_s, sampling_rate, name="--epoch-end")
+ if end_offset <= start_offset:
+ raise CliError("--epoch-end must be after --epoch-start")
+ if recording_samples < 1 or recording_samples > MAX_ROWS:
+ raise CliError(f"--recording-samples must be between 1 and {MAX_ROWS}")
+
+ baseline: dict[str, Any] | None = None
+ if (baseline_start_s is None) != (baseline_end_s is None):
+ raise CliError("provide both --baseline-start and --baseline-end")
+ if baseline_start_s is not None and baseline_end_s is not None:
+ baseline_start = _sample_offset(
+ baseline_start_s, sampling_rate, name="--baseline-start"
+ )
+ baseline_end = _sample_offset(
+ baseline_end_s, sampling_rate, name="--baseline-end"
+ )
+ if not start_offset <= baseline_start < baseline_end <= end_offset:
+ raise CliError("baseline must be a nonempty subset of the epoch")
+ if baseline_end > 0:
+ raise CliError("baseline must not extend after event onset")
+ baseline = {
+ "end_offset_samples_exclusive": baseline_end,
+ "end_s_exclusive": baseline_end_s,
+ "sample_count": baseline_end - baseline_start,
+ "start_offset_samples": baseline_start,
+ "start_s": baseline_start_s,
+ }
+
+ rows: list[dict[str, Any]] = []
+ invalid = 0
+ for ordinal, onset in enumerate(events, start=1):
+ start = onset + start_offset
+ end = onset + end_offset
+ before = max(0, -start)
+ after = max(0, end - recording_samples)
+ complete = before == 0 and after == 0
+ if not complete:
+ invalid += 1
+ if boundary_policy == "drop" and not complete:
+ continue
+ rows.append(
+ {
+ "complete": complete,
+ "end_sample_exclusive": end,
+ "event_ordinal": ordinal,
+ "onset_sample": onset,
+ "pad_after_samples": after,
+ "pad_before_samples": before,
+ "start_sample": start,
+ }
+ )
+ if boundary_policy == "error" and invalid:
+ raise CliError(f"{invalid} event(s) would cross recording boundaries")
+
+ warnings: list[str] = []
+ if events != sorted(events):
+ warnings.append("event onsets are not sorted")
+ if len(events) != len(set(events)):
+ warnings.append("duplicate event onsets are present")
+ if invalid:
+ warnings.append(
+ f"{invalid} event(s) cross a boundary; NeuroKit2 0.2.13 pads "
+ "non-integer signal columns with NaN"
+ )
+
+ return {
+ "baseline": baseline,
+ "boundary_policy": boundary_policy,
+ "event_count_input": len(events),
+ "event_count_output": len(rows),
+ "events": rows,
+ "indexing": {
+ "event_onsets": "zero-based sample indices",
+ "window": "[start_sample, end_sample_exclusive)",
+ },
+ "neurokit2_epoch_note": (
+ "epochs_create() slices the end sample exclusively but labels its "
+ "floating time index with an inclusive epochs_end endpoint. Its "
+ "baseline_correction=True subtracts the mean from epoch start through "
+ "t=0; use manual correction for a narrower baseline."
+ ),
+ "recording_samples": recording_samples,
+ "sampling_rate_hz": sampling_rate,
+ "window": {
+ "end_offset_samples_exclusive": end_offset,
+ "end_s_exclusive": epoch_end_s,
+ "sample_count": end_offset - start_offset,
+ "start_offset_samples": start_offset,
+ "start_s": epoch_start_s,
+ },
+ "warnings": warnings,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan zero-based, sample-exact event epochs and boundary handling. "
+ "No signal values or NeuroKit2 imports are required."
+ )
+ )
+ source = parser.add_mutually_exclusive_group(required=True)
+ source.add_argument("--events", help="comma-separated onsets")
+ source.add_argument("--events-csv", help="bounded local CSV containing onsets")
+ parser.add_argument("--onset-column", default="onset")
+ parser.add_argument(
+ "--event-unit", choices=("samples", "seconds"), default="samples"
+ )
+ parser.add_argument("--sampling-rate", type=float, required=True, help="Hz")
+ parser.add_argument("--recording-samples", type=int, required=True)
+ parser.add_argument("--epoch-start", type=float, required=True, help="seconds")
+ parser.add_argument("--epoch-end", type=float, required=True, help="seconds")
+ parser.add_argument("--baseline-start", type=float, help="seconds")
+ parser.add_argument("--baseline-end", type=float, help="seconds")
+ parser.add_argument(
+ "--boundary-policy",
+ choices=("report", "drop", "error"),
+ default="report",
+ )
+ parser.add_argument("--root", default=".")
+ parser.add_argument(
+ "--deidentified",
+ action="store_true",
+ help="required with --events-csv",
+ )
+ parser.add_argument("--max-events", type=int, default=MAX_EVENTS)
+ parser.add_argument("--output", help="optional local .json report")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ sampling_rate = finite_float(
+ args.sampling_rate,
+ name="--sampling-rate",
+ minimum=0.01,
+ maximum=1_000_000.0,
+ )
+ epoch_start = finite_float(args.epoch_start, name="--epoch-start")
+ epoch_end = finite_float(args.epoch_end, name="--epoch-end")
+ baseline_start = (
+ finite_float(args.baseline_start, name="--baseline-start")
+ if args.baseline_start is not None
+ else None
+ )
+ baseline_end = (
+ finite_float(args.baseline_end, name="--baseline-end")
+ if args.baseline_end is not None
+ else None
+ )
+ if not 1 <= args.max_events <= MAX_EVENTS:
+ raise CliError(f"--max-events must be between 1 and {MAX_EVENTS}")
+
+ if args.events_csv:
+ require_deidentified(args.deidentified)
+ path = checked_input_file(
+ args.events_csv,
+ root=args.root,
+ suffixes={".csv"},
+ max_bytes=MAX_CSV_BYTES,
+ )
+ data, _, row_count = read_numeric_columns(
+ path,
+ [args.onset_column],
+ max_rows=args.max_events,
+ )
+ if row_count > args.max_events:
+ raise CliError(f"event count exceeds {args.max_events}")
+ values = [float(value) for value in data[args.onset_column]]
+ else:
+ values = _parse_events(args.events)
+ if len(values) > args.max_events:
+ raise CliError(f"event count exceeds {args.max_events}")
+
+ event_samples = _event_samples(
+ values,
+ unit=args.event_unit,
+ sampling_rate=sampling_rate,
+ )
+ report = plan(
+ event_samples,
+ recording_samples=args.recording_samples,
+ sampling_rate=sampling_rate,
+ epoch_start_s=epoch_start,
+ epoch_end_s=epoch_end,
+ baseline_start_s=baseline_start,
+ baseline_end_s=baseline_end,
+ boundary_policy=args.boundary_policy,
+ )
+ report["input_event_unit"] = args.event_unit
+ report["path_redacted"] = True
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/scripts/validate_multimodal.py b/skills/neurokit2/scripts/validate_multimodal.py
new file mode 100644
index 00000000..1ef8ca72
--- /dev/null
+++ b/skills/neurokit2/scripts/validate_multimodal.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python3
+"""Validate bounded multimodal stream schemas and temporal alignment."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import re
+import statistics
+from itertools import pairwise
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ CliError,
+ checked_input_file,
+ checked_root,
+ emit_json,
+ finite_float,
+ load_json_object,
+ read_numeric_columns,
+ require_deidentified,
+ run_cli,
+ validate_keys,
+)
+
+MAX_STREAMS = 16
+NAME_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,63}$")
+SYNC_METHODS = {
+ "hardware_trigger",
+ "shared_clock",
+ "timestamp",
+ "validated_manual",
+}
+
+
+def _stream_profile(
+ stream: dict[str, Any],
+ *,
+ root: Path,
+ max_rows: int,
+) -> tuple[dict[str, Any], list[str], list[str]]:
+ validate_keys(
+ stream,
+ allowed={
+ "name",
+ "path",
+ "value_column",
+ "time_column",
+ "sampling_rate_hz",
+ "unit",
+ "start_time_s",
+ },
+ required={"name", "path", "value_column", "sampling_rate_hz", "unit"},
+ context="stream",
+ )
+ name = stream["name"]
+ if not isinstance(name, str) or not NAME_PATTERN.fullmatch(name):
+ raise CliError("stream name must be a short identifier beginning with a letter")
+ for key in ("path", "value_column", "unit"):
+ if not isinstance(stream[key], str) or not stream[key].strip():
+ raise CliError(f"stream {name!r} {key} must be a nonempty string")
+ if len(stream["unit"]) > 32:
+ raise CliError(f"stream {name!r} unit is too long")
+ time_column = stream.get("time_column")
+ if time_column is not None and (
+ not isinstance(time_column, str) or not time_column.strip()
+ ):
+ raise CliError(f"stream {name!r} time_column must be a nonempty string")
+ if time_column is not None and "start_time_s" in stream:
+ raise CliError(
+ f"stream {name!r} must not combine time_column with start_time_s"
+ )
+ declared_rate = finite_float(
+ stream["sampling_rate_hz"],
+ name=f"{name}.sampling_rate_hz",
+ minimum=0.01,
+ maximum=1_000_000.0,
+ )
+ start_time = (
+ finite_float(stream["start_time_s"], name=f"{name}.start_time_s")
+ if "start_time_s" in stream
+ else 0.0
+ )
+ path = checked_input_file(
+ stream["path"],
+ root=root,
+ suffixes={".csv"},
+ max_bytes=MAX_CSV_BYTES,
+ )
+ columns = [stream["value_column"]]
+ if time_column is not None:
+ columns.append(time_column)
+ values, _, row_count = read_numeric_columns(
+ path,
+ columns,
+ max_rows=max_rows,
+ allow_missing=True,
+ )
+ signal = values[stream["value_column"]]
+ missing_count = sum(value is None for value in signal)
+ finite_signal = [float(value) for value in signal if value is not None]
+ flat_count = sum(
+ current == previous for previous, current in pairwise(finite_signal)
+ )
+ flat_fraction = (
+ flat_count / (len(finite_signal) - 1) if len(finite_signal) > 1 else None
+ )
+ errors: list[str] = []
+ warnings: list[str] = []
+ observed_rate: float | None = None
+ interval_jitter: float | None = None
+
+ if time_column is not None:
+ raw_times = values[time_column]
+ if any(value is None for value in raw_times):
+ errors.append("time column contains missing values")
+ times = [float(value) for value in raw_times if value is not None]
+ else:
+ times = [float(value) for value in raw_times]
+ if len(times) >= 2:
+ deltas = [current - previous for previous, current in pairwise(times)]
+ if any(delta <= 0 for delta in deltas):
+ errors.append("timestamps are not strictly increasing")
+ positive = [delta for delta in deltas if delta > 0]
+ if positive:
+ median_delta = statistics.median(positive)
+ observed_rate = 1.0 / median_delta
+ interval_jitter = max(
+ abs(delta - median_delta) / median_delta for delta in positive
+ )
+ start_time = times[0]
+ end_time = times[-1]
+ else:
+ errors.append("fewer than two valid timestamps")
+ end_time = start_time
+ else:
+ end_time = start_time + (row_count - 1) / declared_rate
+
+ if observed_rate is not None:
+ relative_rate_error = abs(observed_rate - declared_rate) / declared_rate
+ if relative_rate_error > 0.01:
+ errors.append(
+ "observed timestamp rate differs from declared rate by more than 1%"
+ )
+ if interval_jitter is not None and interval_jitter > 0.01:
+ warnings.append("timestamp interval jitter exceeds 1% of the median")
+ if missing_count:
+ warnings.append(f"{missing_count} signal values are missing")
+ if flat_fraction is not None and flat_fraction > 0.20:
+ warnings.append("more than 20% of adjacent finite signal values are identical")
+
+ profile = {
+ "declared_sampling_rate_hz": declared_rate,
+ "duration_s": max(0.0, end_time - start_time),
+ "end_time_s": end_time,
+ "flat_transition_fraction": flat_fraction,
+ "missing_count": missing_count,
+ "name": name,
+ "observed_sampling_rate_hz": observed_rate,
+ "path_redacted": True,
+ "row_count": row_count,
+ "start_time_s": start_time,
+ "timestamp_maximum_relative_jitter": interval_jitter,
+ "unit": stream["unit"],
+ }
+ return profile, errors, warnings
+
+
+def validate_manifest(
+ document: dict[str, Any],
+ *,
+ root: Path,
+ max_rows: int,
+) -> dict[str, Any]:
+ validate_keys(
+ document,
+ allowed={"schema_version", "streams", "alignment"},
+ required={"schema_version", "streams", "alignment"},
+ context="manifest",
+ )
+ if document["schema_version"] != "1.0":
+ raise CliError("schema_version must be '1.0'")
+ streams = document["streams"]
+ if not isinstance(streams, list) or not 1 <= len(streams) <= MAX_STREAMS:
+ raise CliError(f"streams must contain 1 to {MAX_STREAMS} objects")
+ if any(not isinstance(stream, dict) for stream in streams):
+ raise CliError("every stream must be an object")
+ alignment = document["alignment"]
+ if not isinstance(alignment, dict):
+ raise CliError("alignment must be an object")
+ validate_keys(
+ alignment,
+ allowed={
+ "reference_stream",
+ "synchronization",
+ "max_start_offset_ms",
+ "minimum_overlap_s",
+ },
+ required={
+ "reference_stream",
+ "synchronization",
+ "max_start_offset_ms",
+ "minimum_overlap_s",
+ },
+ context="alignment",
+ )
+ if alignment["synchronization"] not in SYNC_METHODS:
+ raise CliError(
+ "alignment.synchronization must be one of: "
+ + ", ".join(sorted(SYNC_METHODS))
+ )
+ max_offset_ms = finite_float(
+ alignment["max_start_offset_ms"],
+ name="alignment.max_start_offset_ms",
+ minimum=0.0,
+ maximum=60_000.0,
+ )
+ minimum_overlap_s = finite_float(
+ alignment["minimum_overlap_s"],
+ name="alignment.minimum_overlap_s",
+ minimum=0.0,
+ maximum=31_536_000.0,
+ )
+
+ profiles: list[dict[str, Any]] = []
+ errors: list[str] = []
+ warnings: list[str] = []
+ for index, stream in enumerate(streams, start=1):
+ try:
+ profile, stream_errors, stream_warnings = _stream_profile(
+ stream, root=root, max_rows=max_rows
+ )
+ except CliError as exc:
+ raise CliError(f"stream {index}: {exc}") from exc
+ profiles.append(profile)
+ errors.extend(f"{profile['name']}: {message}" for message in stream_errors)
+ warnings.extend(f"{profile['name']}: {message}" for message in stream_warnings)
+
+ names = [profile["name"] for profile in profiles]
+ if len(names) != len(set(names)):
+ raise CliError("stream names must be unique")
+ reference_name = alignment["reference_stream"]
+ if reference_name not in names:
+ raise CliError("alignment.reference_stream is not a stream name")
+ reference = next(
+ profile for profile in profiles if profile["name"] == reference_name
+ )
+
+ start_offsets_ms: dict[str, float] = {}
+ for profile in profiles:
+ offset_ms = (profile["start_time_s"] - reference["start_time_s"]) * 1000.0
+ start_offsets_ms[profile["name"]] = offset_ms
+ if abs(offset_ms) > max_offset_ms:
+ errors.append(
+ f"{profile['name']}: start offset {offset_ms:.6g} ms exceeds "
+ f"{max_offset_ms:.6g} ms"
+ )
+ overlap_start = max(profile["start_time_s"] for profile in profiles)
+ overlap_end = min(profile["end_time_s"] for profile in profiles)
+ overlap_s = max(0.0, overlap_end - overlap_start)
+ if overlap_s < minimum_overlap_s:
+ errors.append(
+ f"common overlap {overlap_s:.6g} s is below {minimum_overlap_s:.6g} s"
+ )
+
+ rates = [profile["declared_sampling_rate_hz"] for profile in profiles]
+ counts = [profile["row_count"] for profile in profiles]
+ same_rate = all(
+ math.isclose(rate, rates[0], rel_tol=1e-9, abs_tol=1e-12) for rate in rates[1:]
+ )
+ same_count = all(count == counts[0] for count in counts[1:])
+ no_missing = all(profile["missing_count"] == 0 for profile in profiles)
+ starts_within_sample = all(
+ abs(start_offsets_ms[profile["name"]])
+ <= (500.0 / profile["declared_sampling_rate_hz"])
+ for profile in profiles
+ )
+ bio_process_compatible = (
+ same_rate and same_count and no_missing and starts_within_sample and not errors
+ )
+ if not same_rate:
+ warnings.append(
+ "native sampling rates differ; process at native rates, align clocks, "
+ "then resample continuous channels to an explicit common grid"
+ )
+ if not bio_process_compatible:
+ warnings.append(
+ "do not pass these streams directly to bio_process(); NeuroKit2 "
+ "0.2.13 does not synchronize or automatically resample inputs"
+ )
+
+ return {
+ "alignment": {
+ "common_overlap_s": overlap_s,
+ "max_start_offset_ms": max_offset_ms,
+ "minimum_overlap_s": minimum_overlap_s,
+ "reference_stream": reference_name,
+ "start_offsets_ms": start_offsets_ms,
+ "synchronization": alignment["synchronization"],
+ },
+ "bio_process_direct_input_compatible": bio_process_compatible,
+ "errors": errors,
+ "path_redacted": True,
+ "schema_version": "1.0",
+ "streams": profiles,
+ "valid": not errors,
+ "warnings": warnings,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a strict JSON manifest of bounded local biosignal CSV "
+ "streams, units, clocks, rates, starts, overlap, and missingness."
+ )
+ )
+ parser.add_argument("--manifest", required=True, help="local .json manifest")
+ parser.add_argument("--root", default=".", help="existing local I/O boundary")
+ parser.add_argument("--max-rows", type=int, default=MAX_ROWS)
+ parser.add_argument(
+ "--deidentified",
+ action="store_true",
+ help="confirm direct and reviewed quasi-identifiers were removed",
+ )
+ parser.add_argument("--output", help="optional local .json report")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ require_deidentified(args.deidentified)
+ if not 1 <= args.max_rows <= MAX_ROWS:
+ raise CliError(f"--max-rows must be between 1 and {MAX_ROWS}")
+ root = checked_root(args.root)
+ document = load_json_object(args.manifest, root=root)
+ report = validate_manifest(document, root=root, max_rows=args.max_rows)
+ emit_json(report, output=args.output, root=root, force=args.force)
+ if not report["valid"]:
+ raise CliError(
+ f"multimodal validation failed with {len(report['errors'])} error(s)"
+ )
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/neurokit2/tests/test_scripts.py b/skills/neurokit2/tests/test_scripts.py
new file mode 100644
index 00000000..90520519
--- /dev/null
+++ b/skills/neurokit2/tests/test_scripts.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python3
+"""Dependency-free and pinned-runtime tests for NeuroKit2 skill helpers."""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+REFERENCES = SKILL_ROOT / "references"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common
+import ecg_hrv_pipeline
+import eda_pipeline
+import generate_synthetic
+import inspect_signal
+import plan_epochs
+import validate_multimodal
+
+HAS_NEUROKIT2 = importlib.util.find_spec("neurokit2") is not None
+
+
+def run_script(
+ name: str,
+ *arguments: str,
+ cwd: Path | None = None,
+ without_site_packages: bool = True,
+) -> subprocess.CompletedProcess[str]:
+ command = [sys.executable]
+ if without_site_packages:
+ command.append("-S")
+ command.extend([str(SCRIPTS / name), *arguments])
+ environment = os.environ.copy()
+ environment["PYTHONDONTWRITEBYTECODE"] = "1"
+ return subprocess.run(
+ command,
+ cwd=cwd,
+ env=environment,
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+
+
+class SafetyAndManifestTests(unittest.TestCase):
+ def test_scripts_parse_without_dynamic_execution_or_network_imports(self) -> None:
+ banned_imports = {
+ "aiohttp",
+ "httpx",
+ "importlib",
+ "pickle",
+ "requests",
+ "socket",
+ "subprocess",
+ "urllib",
+ }
+ banned_calls = {"eval", "exec", "compile", "__import__"}
+ shadow_names = {
+ "csv.py",
+ "json.py",
+ "neurokit2.py",
+ "numpy.py",
+ "pandas.py",
+ "pathlib.py",
+ "pickle.py",
+ }
+ self.assertFalse({path.name for path in SCRIPTS.glob("*.py")} & shadow_names)
+ for path in sorted(SCRIPTS.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ roots = {alias.name.split(".", 1)[0] for alias in node.names}
+ self.assertFalse(roots & banned_imports, path.name)
+ if isinstance(node, ast.ImportFrom) and node.module:
+ self.assertNotIn(
+ node.module.split(".", 1)[0], banned_imports, path.name
+ )
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ self.assertNotIn(node.func.id, banned_calls, path.name)
+ if isinstance(node, ast.Attribute):
+ self.assertFalse(
+ isinstance(node.value, ast.Name)
+ and node.value.id == "os"
+ and node.attr in {"environ", "getenv"},
+ path.name,
+ )
+ self.assertNotIn(".pkl", path.read_text(encoding="utf-8").lower())
+
+ def test_every_cli_help_works_without_site_packages(self) -> None:
+ for path in sorted(SCRIPTS.glob("*.py")):
+ if path.name == "_common.py":
+ continue
+ with self.subTest(script=path.name):
+ result = run_script(path.name, "--help")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("usage:", result.stdout)
+ self.assertNotIn("Traceback", result.stderr)
+
+ def test_build_parsers_are_dependency_free(self) -> None:
+ modules = (
+ ecg_hrv_pipeline,
+ eda_pipeline,
+ generate_synthetic,
+ inspect_signal,
+ plan_epochs,
+ validate_multimodal,
+ )
+ for module in modules:
+ with self.subTest(module=module.__name__):
+ self.assertIn("usage:", module.build_parser().format_help())
+
+ def test_strict_local_io_rejects_url_symlink_duplicates_and_nan(self) -> None:
+ with self.assertRaises(_common.CliError):
+ _common.checked_input_file(
+ "https://example.invalid/signal.csv",
+ root=".",
+ suffixes={".csv"},
+ max_bytes=1024,
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ duplicate = root / "duplicate.json"
+ duplicate.write_text('{"x": 1, "x": 2}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(duplicate, root=root)
+ nonfinite = root / "nonfinite.json"
+ nonfinite.write_text('{"x": NaN}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(nonfinite, root=root)
+ real = root / "real.csv"
+ real.write_text("x\n1\n", encoding="utf-8")
+ link = root / "link.csv"
+ try:
+ link.symlink_to(real)
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with self.assertRaises(_common.CliError):
+ _common.checked_input_file(
+ link,
+ root=root,
+ suffixes={".csv"},
+ max_bytes=1024,
+ )
+
+ def test_skill_version_license_references_and_progressive_disclosure(self) -> None:
+ skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertIn('metadata:\n version: "1.1"', skill)
+ self.assertIn("license: MIT", skill)
+ self.assertIn("compatibility:", skill)
+ self.assertIn('uv pip install "neurokit2==0.2.13"', skill)
+ self.assertNotIn("zipball", skill.lower())
+ self.assertLess(len(skill.splitlines()), 500)
+ self.assertEqual(
+ {path.name for path in REFERENCES.glob("*.md")},
+ {
+ "bio_module.md",
+ "complexity.md",
+ "ecg_cardiac.md",
+ "eda.md",
+ "eeg.md",
+ "emg.md",
+ "eog.md",
+ "epochs_events.md",
+ "hrv.md",
+ "ppg.md",
+ "rsp.md",
+ "signal_processing.md",
+ },
+ )
+ for path in REFERENCES.glob("*.md"):
+ self.assertIn("2026-07-23", path.read_text(encoding="utf-8"), path.name)
+
+
+class DependencyFreeWorkflowTests(unittest.TestCase):
+ def test_synthetic_generation_is_deterministic_and_inspectable(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ first = run_script(
+ "generate_synthetic.py",
+ "--output",
+ "first.csv",
+ "--root",
+ str(root),
+ "--duration",
+ "4",
+ "--sampling-rate",
+ "100",
+ "--seed",
+ "7",
+ )
+ second = run_script(
+ "generate_synthetic.py",
+ "--output",
+ "second.csv",
+ "--root",
+ str(root),
+ "--duration",
+ "4",
+ "--sampling-rate",
+ "100",
+ "--seed",
+ "7",
+ )
+ self.assertEqual(first.returncode, 0, first.stderr)
+ self.assertEqual(second.returncode, 0, second.stderr)
+ first_report = json.loads(first.stdout)
+ second_report = json.loads(second.stdout)
+ self.assertEqual(first_report["sha256"], second_report["sha256"])
+ self.assertEqual(
+ (root / "first.csv").read_bytes(),
+ (root / "second.csv").read_bytes(),
+ )
+ self.assertEqual(stat.S_IMODE((root / "first.csv").stat().st_mode), 0o600)
+ self.assertNotIn(str(root), first.stdout)
+
+ inspected = run_script(
+ "inspect_signal.py",
+ "--input",
+ "first.csv",
+ "--root",
+ str(root),
+ "--columns",
+ "ecg,rsp,eda,trigger",
+ "--time-column",
+ "time_s",
+ "--sampling-rate",
+ "100",
+ "--deidentified",
+ )
+ self.assertEqual(inspected.returncode, 0, inspected.stderr)
+ report = json.loads(inspected.stdout)
+ self.assertEqual(report["row_count"], 400)
+ self.assertAlmostEqual(report["observed_sampling_rate_hz"], 100.0)
+ self.assertEqual(report["path_redacted"], True)
+
+ def test_epoch_planner_reports_sample_exact_boundaries(self) -> None:
+ result = run_script(
+ "plan_epochs.py",
+ "--events",
+ "100,500,990",
+ "--sampling-rate",
+ "100",
+ "--recording-samples",
+ "1000",
+ "--epoch-start",
+ "-0.2",
+ "--epoch-end",
+ "0.5",
+ "--baseline-start",
+ "-0.2",
+ "--baseline-end",
+ "0",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertEqual(report["window"]["sample_count"], 70)
+ self.assertEqual(report["baseline"]["sample_count"], 20)
+ self.assertTrue(report["events"][0]["complete"])
+ self.assertFalse(report["events"][-1]["complete"])
+ self.assertEqual(report["events"][-1]["pad_after_samples"], 40)
+
+ def test_multimodal_validator_detects_resampling_need(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "ecg.csv").write_text(
+ "time_s,ECG\n"
+ + "".join(f"{index / 100:.2f},{index % 7}\n" for index in range(101)),
+ encoding="utf-8",
+ )
+ (root / "rsp.csv").write_text(
+ "time_s,RSP\n"
+ + "".join(f"{index / 50:.2f},{index % 5}\n" for index in range(51)),
+ encoding="utf-8",
+ )
+ manifest = {
+ "schema_version": "1.0",
+ "streams": [
+ {
+ "name": "ECG",
+ "path": "ecg.csv",
+ "value_column": "ECG",
+ "time_column": "time_s",
+ "sampling_rate_hz": 100,
+ "unit": "mV",
+ },
+ {
+ "name": "RSP",
+ "path": "rsp.csv",
+ "value_column": "RSP",
+ "time_column": "time_s",
+ "sampling_rate_hz": 50,
+ "unit": "a.u.",
+ },
+ ],
+ "alignment": {
+ "reference_stream": "ECG",
+ "synchronization": "shared_clock",
+ "max_start_offset_ms": 1,
+ "minimum_overlap_s": 0.9,
+ },
+ }
+ (root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
+ result = run_script(
+ "validate_multimodal.py",
+ "--manifest",
+ "manifest.json",
+ "--root",
+ str(root),
+ "--deidentified",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertTrue(report["valid"])
+ self.assertFalse(report["bio_process_direct_input_compatible"])
+ self.assertGreaterEqual(len(report["warnings"]), 1)
+
+
[email protected](HAS_NEUROKIT2, "pinned NeuroKit2 is not installed")
+class PinnedNeuroKitSmokeTests(unittest.TestCase):
+ def test_pinned_version_and_synthetic_ecg_pipeline(self) -> None:
+ from importlib.metadata import version
+
+ self.assertEqual(version("neurokit2"), _common.NEUROKIT2_VERSION)
+ result = run_script(
+ "ecg_hrv_pipeline.py",
+ "--synthetic",
+ "--sampling-rate",
+ "250",
+ "--duration",
+ "30",
+ "--heart-rate",
+ "70",
+ "--domains",
+ "time",
+ without_site_packages=False,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertEqual(report["neurokit2_version"], "0.2.13")
+ self.assertGreater(report["detected_r_peaks"], 20)
+ self.assertIn("ECG_Quality", report["output_schema_observed"]["signal_columns"])
+
+ def test_pinned_synthetic_eda_pipeline(self) -> None:
+ result = run_script(
+ "eda_pipeline.py",
+ "--synthetic",
+ "--sampling-rate",
+ "100",
+ "--duration",
+ "20",
+ "--scr-number",
+ "3",
+ without_site_packages=False,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertEqual(report["neurokit2_version"], "0.2.13")
+ self.assertIn("EDA_Phasic", report["output_schema_observed"]["signal_columns"])
+
+
+if __name__ == "__main__":
+ unittest.main()