AgentStack
SKILL unreviewed Apache-2.0 Self-run

ClaudeEEG

skill-krish-mal15-claudeeeg-claudeeeg · by Krish-mal15

Expert EEG/MEG analysis, BCI development, and neuroscience signal processing — from raw recordings to production-grade models. Covers theory, preprocessing pipelines, ML/DL modeling, real-time classification, statistical analysis, and data ingestion.

No reviews yet
0 installs
9 views
0.0% view→install

Install

$ agentstack add skill-krish-mal15-claudeeeg-claudeeeg

Open-source listing — not yet scanned by AgentStack. Follow the source repository for install instructions.

Security review

⚠ Flagged

1 finding(s); flagged for manual review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures
  • high Dangerous shell/eval execution.

What it can access

  • Network access No
  • Filesystem access Used
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution Used

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of ClaudeEEG? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

ClaudeEEG

> A second brain for automated EEG analysis — from messy recordings to production-grade models.


Overview

Load this skill whenever the user's request involves EEG data, neuroscience signal processing, BCI pipelines, or any brain-data analysis task. This document is structured as a living reference: read the relevant section(s) for each task and reason from first principles before generating code or recommendations. Always match the tool to the scientific question, not just user familiarity.

Skill trigger keywords: EEG, MEG, electrophysiology, brain-computer interface, BCI, ICA, ERP, epochs, artifact removal, EEGLAB, MNE, braindecode, NeuroPype, neural decoding, oscillations, frequency bands, power spectral density, source localization, motor imagery, P300, SSVEP, neurofeedback, neuro.

For detailed code examples, see the /scripts subfolder and for detailed documentation, see the /references subfolder.


1. EEG THEORY FOUNDATIONS

Understanding these principles is non-negotiable — they directly inform every preprocessing and modeling decision.

1.1 What EEG Actually Measures

EEG records the summed postsynaptic potentials of large pyramidal neuron populations in the neocortex, measured at the scalp surface. Key implications:

  • Volume conduction: Signals are spatially smeared by the skull, scalp, and CSF before reaching electrodes. A source in one region appears spread across many channels. This is why raw channel signals cannot be naively treated as spatially independent.
  • Signal amplitude: Typically 10–100 µV on the scalp. Amplitudes are inversely related to frequency — slow waves are larger, fast waves are smaller.
  • Temporal resolution: Millisecond-precision, making EEG ideal for studying rapid neural dynamics (ERPs, oscillatory bursts). Spatial resolution, however, is poor (centimeter-scale at best).
  • EEG reflects network dynamics, not individual neuron activity. Gamma oscillations (30–80 Hz), for example, can reflect synchronous firing across distributed populations — not just local activity.

1.2 Frequency Bands — Science, Not Just Labels

Frequency band boundaries vary in the literature (see Sapien Labs 2020 review on this inconsistency). Use these as biological priors, not hard cutoffs:

|Band|Range (common)|Functional correlates|Key caveats| |---|---|---|---| |Delta|0.5–4 Hz|Deep sleep, motivational processing, correlates with P300 dopamine reward; abnormal in awake adults|Highly susceptible to movement/EMG artifacts at low frequencies| |Theta|4–8 Hz|Memory encoding (hippocampal), spatial navigation, working memory (theta-gamma coupling), emotional valence|Normal in drowsiness and children; theta-gamma nesting = ~4–7 items in working memory| |Alpha|8–13 Hz|Inhibition of irrelevant cortical areas, relaxed wakefulness, attentional gating; posterior dominant rhythm (PDR) in healthy adults|Alpha suppression (ERD) occurs on eyes opening or task engagement; individual alpha frequency (IAF) varies and should be computed per-subject| |Beta|13–30 Hz|Active thinking, motor planning, sensorimotor rhythm (SMR ~12–15 Hz); ERSP during motor execution|Heavily contaminated by muscle artifact, especially frontally| |Gamma|30–80 Hz|Feature binding, perceptual integration, attentional focus, high-level cognition|Virtually impossible to isolate cleanly on scalp EEG without extreme care — muscle artifacts occupy 20–300 Hz and overlap gamma entirely| |High-gamma / HFO|>80 Hz|Epileptic high-frequency oscillations; accessible mainly via intracranial EEG|Scalp gamma should be interpreted with extreme skepticism|

Critical gamma warning: The muscle artifact frequency range (20–300 Hz) fully overlaps gamma. Any gamma findings on scalp EEG without rigorous EMG rejection should be treated as artifact-contaminated. AMICA + ICLabel + manual inspection is the minimum bar.

Band inconsistency: Studies define "theta" with start points anywhere from 2.5–6.5 Hz. Always report your exact frequency windows. Never assume a paper's "theta" matches yours.

1.3 Cross-Frequency Coupling (CFC)

Nested oscillations are functionally meaningful, not just spectral curiosities:

  • Theta-gamma coupling: Each theta cycle (~125 ms) contains ~4–7 gamma sub-cycles, each representing one item in working memory. This is the mechanistic basis for the 7±2 working memory limit.
  • Delta-theta coupling: Delta phase organizes theta bursts — relevant in sleep and deep cognitive states.
  • Phase-Amplitude Coupling (PAC): The phase of a slow oscillation modulates the amplitude of a faster one. Measure with modulation index (MI) or mean vector length. MNE has mne.connectivity tools for this.
  • Beta-gamma PAC in basal ganglia: Relevant in Parkinson's research and motor BCI.

1.4 Event-Related Potentials (ERPs) — Core Components

ERPs are voltage deflections time-locked to stimuli, extracted by trial averaging (which cancels non-phase-locked noise):

|Component|Latency|Scalp distribution|Cognitive correlate| |---|---|---|---| |N100 (N1)|~100 ms|Frontocentral|Sensory processing, auditory cortex activation| |P200 (P2)|~200 ms|Frontocentral|Attentional modulation| |N200 (N2)|~200 ms|Frontocentral|Conflict detection, inhibition (No-Go tasks)| |P300 (P3b)|~300–600 ms|Parietal (Pz)|Context updating, target detection; core of P300-BCI| |N400|~400 ms|Centro-parietal|Semantic incongruity| |LRP|~150 ms before response|Contralateral motor|Lateralized readiness potential — motor planning| |MMN|~150–250 ms|Frontocentral|Mismatch negativity — automatic deviance detection|

Baseline correction is essential: subtract mean voltage of a pre-stimulus window (typically –200 to 0 ms). This removes DC offsets. The choice of baseline period affects ERP shape significantly.

1.5 Event-Related Desynchronization/Synchronization (ERD/ERS)

Not phase-locked power changes around events:

  • ERD (power decrease): Alpha/beta decrease during motor execution or preparation. Contralateral to the moved limb.
  • ERS (power increase): Beta rebound post-movement — reflects cortical "idling."
  • Measure with ERSP (event-related spectral perturbation) — time-frequency power relative to baseline.
  • ERD/ERS are the core signals for motor imagery BCI.

1.6 Electrode Systems and Montages

  • 10–20 system: Standard 19-channel clinical montage. Channel names encode location (F=frontal, C=central, P=parietal, O=occipital, T=temporal; z=midline, odd=left, even=right).
  • 10–10 and 10–5 systems: Denser montages for high-density research EEG (64, 128, 256 channels).
  • Reference electrode matters enormously: All EEG is a voltage difference between the active electrode and a reference. Common choices:
  • Linked mastoids (A1+A2): Reduces ear artifacts but biases toward temporal signals.
  • Average reference (CAR): Subtracts mean of all electrodes; good when channels cover full scalp, problematic with sparse montages or many bad channels.
  • REST (Reference Electrode Standardization Technique): Approximates an "infinity" reference using a forward model; increasingly recommended for source analysis.
  • Laplacian (CSD): Current source density — emphasizes local activity, reduces volume conduction. Ideal for high-density, spatially fine-grained analysis.

2. THE GOLD-STANDARD PREPROCESSING PIPELINE

Follow this order. Deviating from it requires scientific justification.

Phase 0: Data Inspection and Documentation

Before touching the data:

  1. Check sampling rate, number of channels, recording duration, event codes.
  2. Visualize raw traces — look for dead channels, saturation, excessive drift.
  3. Document electrode impedances if available (target 4 SD deviation from mean channel power. Mark before any filtering.
# MNE approach
from mne.preprocessing import find_bad_channels_maxwell
# Or manual:
raw.info['bads'] = ['Fp1', 'AF7']  # flagged visually or algorithmically

# EEGLAB equivalent: pop_rejchan() with kurtosis/probability threshold

Step 1.2 — Line noise removal

Choose based on context:

  • Notch filter (50 or 60 Hz): Simple, but introduces ringing and distorts nearby frequencies. Avoid if analysis is near 50/60 Hz.
  • Zapline / DSS-based methods: Preferred. Removes line noise without spectral distortion using data-driven denoising source separation. Available via meegkit in Python.
  • Frequency-domain interpolation: Alternative for stationary line noise.
# Notch (use cautiously)
raw.notch_filter(freqs=[50, 100])

# Zapline via meegkit (preferred for high-quality data)
from meegkit import dss

Phase 2: Filtering

Critical rule: Filter before epoching to avoid edge artifacts in epochs. But fit ICA on filtered data and apply to minimally filtered data (see below).

High-pass filter (drift removal)

  • Standard: 0.5–1 Hz for most analyses.
  • ERP analyses requiring slow components (P300 body, CNV): use 0.1 Hz.
  • For ICA fitting: use 1–2 Hz (ICA decomposition quality degrades with slow drift).
  • Do not use 0.1 Hz for ICA — this is the "dual dataset" trick.

Low-pass filter

  • Anti-aliasing: always apply at half the Nyquist frequency before downsampling.
  • Analysis-specific: 40 Hz suffices for ERP; 100+ Hz for gamma/HFO.

Filter type matters:

  • FIR (recommended): Linear phase, predictable response. Use Hamming windowed sinc (MNE default). Specify length explicitly — longer = sharper rolloff = more temporal smearing.
  • IIR: Faster, but introduces phase distortion. Avoid for ERP timing analyses; acceptable for online/real-time.
# MNE FIR filtering
raw.filter(l_freq=1.0, h_freq=40.0, method='fir', fir_window='hamming')

# For ICA fitting dataset (keep separate from analysis dataset):
raw_for_ica = raw.copy().filter(1.0, 40.0)

Phase 3: Downsampling

Always apply low-pass filter first, then downsample. Target: 2–4× your highest frequency of interest. 256 Hz is standard for ERP; 512 Hz for gamma.

raw.resample(sfreq=256)

Phase 4: Re-referencing

Do this after bad channel removal and before ICA:

# Average reference
raw.set_eeg_reference('average', projection=True)

# REST reference (requires forward model)
# mne.set_eeg_reference(raw, 'REST', ...)

Phase 5: Artifact Removal — The Core Challenge

This is where most analysis quality is won or lost.

5.1 Artifact Source Separator (ASR) — For High-Motion Data

Artifact Subspace Reconstruction removes large transient artifacts (head movements, electrode pops) before ICA. Use when:

  • Mobile EEG / naturalistic paradigms.
  • Moderate-to-high motion artifacts.
  • Running EEGLAB pipelines.

Evidence: ASR before ICA (ASRICA) outperforms ICA alone or ASR after ICA for mobile EEG. The 2024 "skateboarding" study (Callan et al., Frontiers Neuroergonomics) demonstrates this definitively.

ASR is available in EEGLAB as clean_rawdata. In Python, use mne_icalabel ecosystem or pyasr.

5.2 ICA — The Core Tool

ICA decomposes multi-channel EEG into statistically independent components (ICs). Artifacts (eye blinks, heartbeat, muscle) are typically captured in a small number of ICs, which can be removed.

Fundamental requirements:

  • Data must be filtered ≥1 Hz before ICA.
  • Remove gross artifacts (ASR or manual rejection) before ICA — noisy samples degrade decomposition.
  • Sufficient data: aim for ≥20 × n_channels² samples.
  • Number of ICs ≤ rank of data (typically n_channels after bad channel interpolation).

Dual-dataset approach (canonical best practice):

  1. Create Dataset A: high-pass at 1–2 Hz, clean of gross artifacts → fit ICA here.
  2. Create Dataset B: high-pass at 0.1 Hz (preserves slow components) → apply ICA weights from A. This preserves slow ERPs while benefiting from clean ICA decomposition.
# MNE ICA pipeline
from mne.preprocessing import ICA

ica = ICA(n_components=25, method='infomax', fit_params={'extended': True}, random_state=42)
ica.fit(raw_for_ica)

# Auto-label components
from mne_icalabel import label_components
ic_labels = label_components(raw_for_ica, ica, method='iclabel')

# Exclude non-brain components automatically
exclude_idx = [i for i, label in enumerate(ic_labels['labels'])
               if label not in ['brain', 'other'] and ic_labels['y_pred_proba'][i] > 0.8]
ica.exclude = exclude_idx
ica.apply(raw)  # apply to analysis dataset

ICA algorithms:

  • Extended Infomax (MNE default): Handles both sub- and super-Gaussian sources. Reliable.
  • FastICA: Fast, good for quick exploration.
  • AMICA: Best decomposition quality, especially for mobile EEG. Slower. EEGLAB/standalone.
  • SOBI: Second-order statistics; handles non-stationary data well.

IC classification tools:

  • ICLabel (EEGLAB + MNE): CNN trained on thousands of manually labeled ICs. Classifies: brain, eye, muscle, heart, channel noise, line noise, other. Use 'lite' variant for muscle ICs.
  • MARA (EEGLAB): Linear discriminant classifier, older but still used.
  • AutoReject (MNE): Epoch-level rejection, not IC-level — complementary.

Manual IC inspection checklist:

  • Topographic map: focal scalp distribution = brain; bilateral frontal = eye; lateral temporal = muscle; single channel = noise.
  • Time course: periodic = heartbeat (ICA001 often); square waves = eye; high-freq bursts = muscle.
  • Power spectrum: 1/f slope = brain; flat/high-freq = muscle; 60 Hz peak = line noise.

Important 2024 finding: For deep learning decoders, ICA artifact removal may not improve (and sometimes hurts) classification performance compared to raw data (Kang et al., J. Neural Eng. 2024). This does not apply to ERP or spectral analyses where SNR is the bottleneck. Adjust your pipeline based on the downstream task.

5.3 Epoch-Level Artifact Rejection

After ICA, remaining artifacts in individual epochs should be rejected:

from autoreject import AutoReject
ar = AutoReject(random_state=42)
epochs_clean, reject_log = ar.fit_transform(epochs, return_log=True)

Or threshold-based:

reject = dict(eeg=150e-6)  # 150 µV threshold
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, reject=reject)

Phase 6: Epoching

events, event_id = mne.events_from_annotations(raw)
epochs = mne.Epochs(raw, events, event_id={'target': 1, 'nontarget': 2},
                    tmin=-0.2, tmax=0.8,
                    baseline=(-0.2, 0),  # pre-stimulus baseline
                    preload=True)

Baseline correction: Always use a pre-stimulus window. The baseline period should not contain the stimulus response. For very slow components, longer baselines introduce regression-to-mean artifacts.

Phase 7: Bad Channel Interpolation

Interpolate bad channels after the rest of preprocessing but before re-referencing or group analysis. Use spherical spline interpolation:

raw.interpolate_bads(reset_bads=True)

3. LIBRARY REFERENCE GUIDE

3.1 MNE-Python — The Python Standard

When to use: Any Python-based EEG/MEG pipeline. Best-in-class for preprocessing, ERP, time-frequency, and source localization.

Core objects:

  • Raw: Continuous data. raw.get_data() returns (nchannels, ntimes) array.
  • Epochs: Event-locked segmented data. Shape: (nepochs, nchannels, n_times).
  • Evoked: Averaged epochs. Shape: (nchannels, ntimes).
  • Info: Metadata dict — sampling rate, channel names, montage.

Key submodules:

mne.io              # reading raw data (EDF, BrainVision, EDF+, FIF, SET, CNT, etc.)
mne.preprocessing   # ICA, SSP, filtering, Maxwell filtering
mne.epochs          # Epochs class
mne.time_frequency  # Morlet TFR, multitaper PSD, Hilbert
mne.connectivity    # coherence, PLV, WPLI
mne.beamformer      # LCMV, DICS source localization
mne.minimum_norm    # MNE, dSPM, sLORETA inverse solutions
mne.stats           # permutation clu

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [Krish-mal15](https://github.com/Krish-mal15)
- **Source:** [Krish-mal15/ClaudeEEG](https://github.com/Krish-mal15/ClaudeEEG)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.