Skip to content

duhmariya/EpiConnectome

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

EpiConnectome: Source-Space Connectivity and Seizure Severity 🧠⚑

Source-Level Seizure Severity Classification using Graph Attention Networks

Brainhack School 2026 Β· National Central University, Taiwan
Mariya Nissar Β· First Year PhD, Electrical Engineering Β· NCU Taiwan

Python MNE PyTorch License: MIT Brainhack


🎯 What This Project Does

EpiConnectome is an end-to-end, fully reproducible pipeline that:

  1. Takes raw clinical EEG files (EDF format) from epilepsy patients
  2. Applies dSPM source localization to recover 18 cortical regions of interest (ROIs)
  3. Computes wPLI connectivity matrices across theta, alpha, and beta bands
  4. Trains a GATv2 Graph Attention Network to classify seizure severity
  5. Generates interpretable attention maps showing which brain regions drive severity

NOT: "We discovered new epilepsy biomarkers"
YES: "We built a shareable, well-documented pipeline anyone can run on public data"


πŸ“Š Key Results

Band K-Fold Acc K-Fold F1 K-Fold AUC LOSO Bal.Acc LOSO AUC Permutation p
Alpha 97.5% 97.1% 99.2% 95.8% 1.00 (8/12 subj) <0.001
Beta 92.1% 91.4% 98.8% 91.7% 1.00 (7/12 subj) <0.001
Theta 92.1% 92.1% 97.2% 87.5% 1.00 (5/12 subj) <0.001
  • All bands: p<0.001 (0/1000 permutations exceeded the observed value)
  • LOSO AUC=1.00 in all evaluable subjects β€” rank-ordering of severity generalizes across patients
  • GATv2 attention maps reveal frequency-specific cortical propagation patterns

GATv2 classification performance and permutation test significance across theta, alpha, and beta bands Figure 1. GATv2 classification performance (left) and permutation test significance (right) across all three frequency bands.


πŸ” Interim Results & Sanity Checks

This section documents what we found at each pipeline stage β€” to help readers interpret the results and know what to expect when replicating, as well as to check our findings against known neuroscience.

1. Methodological Sanity Check β€” Volume Conduction Removal

The first sanity check is whether dSPM actually removes volume conduction. It does:

Level Mean wPLI (Theta) Interpretation
Channel-level (scalp) 0.646 Inflated by volume conduction
Source-level (dSPM) 0.485 True cortical connectivity

The ~25% drop after source localization is consistent with published literature and confirms dSPM is correctly removing spurious zero-lag interactions. If you replicate this pipeline and do not see this drop, something is wrong with the source localization step.

πŸ“– Replicates: Vinck et al. (2011, NeuroImage) β€” wPLI at source level is systematically lower than sensor-level coherence due to removal of zero-lag interactions.


2. Frequency Band Dominance

Theta band showed the highest overall wPLI connectivity at both channel and source level across all 47 seizures. This is consistent with the established role of theta oscillations in hippocampal-cortical communication and seizure propagation in temporal lobe epilepsy.

πŸ“– Replicates: Mormann et al. (2000, Clinical Neurophysiology) β€” theta-band phase synchronization is a key feature of seizure dynamics in TLE patients.

πŸ“– Supported by: BuzsΓ‘ki & Moser (2013, Nature Neuroscience) β€” theta oscillations coordinate hippocampal-cortical communication.


3. Conceptual Sanity Check β€” Is the High vs Low Difference Real?

Before any classifier, we verified the connectivity difference between High and Low severity seizures is statistically robust using a 1000-permutation test:

  • Observed mean |High βˆ’ Low| wPLI β‰ˆ 0.22–0.28 across all bands
  • Maximum across all 1000 null shuffles β‰ˆ 0.16–0.18
  • The observed effect exceeds the entire null distribution, not just the 95th percentile

High-severity seizures show global cortical hyperconnectivity β€” nearly uniform elevated wPLI across all 18Γ—18 ROI pairs. Low-severity seizures show patchy, lower-magnitude patterns. This global hyperconnectivity during severe seizures is consistent with the concept of pathological hypersynchrony.

πŸ“– Supported by: Jiruska et al. (2013, Journal of Physiology) β€” seizure generation involves pathological hypersynchrony of cortical networks.

Permutation test for the alpha band showing the observed wPLI difference far exceeding the null distribution Figure 2. Permutation test (alpha band) β€” observed difference (orange line) sits entirely outside the null distribution from 1000 shuffles.

Channel connectivity heatmaps comparing Low severity, High severity, and the difference between them in the alpha band Figure 3. Source-level wPLI connectivity (alpha band) β€” Low severity, High severity, and the difference (High βˆ’ Low).

β†’ Full set: results/GATv2_Results_v4/permutation_{band}.png and heatmap_{band}.png for theta, alpha, beta


4. Empirical Sanity Check β€” Subject-Level Consistency

Two patients (PN05, PN07) are consistently high-severity across all three frequency bands:

Patient Alpha wPLI Beta wPLI Theta wPLI Severity
PN07 0.782 0.747 0.829 High (all bands)
PN05 0.749 0.700 0.675 High (all bands)
PN00 0.384 0.370 0.377 Low (all bands)
PN03 0.377 0.365 0.359 Low (all bands)

Cross-band consistency is a strong empirical sanity check β€” if connectivity severity were noise, you would not expect the same patients to rank high across three independent band analyses.

Subject-level seizure connectivity severity heatmap showing mean wPLI per patient across alpha, beta, and theta bands Figure 4. Subject-level mean wPLI across all three bands β€” PN05 and PN07 consistently rank highest.

β†’ Full file: results/GATv2_Results_v4/subject_severity_heatmap.png


5. Attention Map Findings vs Known Neuroscience

GATv2 attention weights after MC Dropout (50 passes) show frequency-specific patterns that align with published neuroscience:

Band Top Attended ROIs Why This Makes Sense Literature
Alpha TMP-R, AUD-R (right temporal/auditory) Alpha desynchronization is a known peri-ictal marker; right temporal dominance consistent with TLE lateralization Klimesch (1999); Pfurtscheller & Lopes da Silva (1999)
Beta MOT-L, TMP-L, MTL-L (left motor/temporal) Beta suppression during/after seizures involves motor and temporal cortex Crone et al. (2006)
Theta SPL-R, IPL-R (right posterior parietal) Theta drives hippocampal-cortical communication; parietal involvement is consistent with seizure propagation networks Mormann et al. (2000)

The medial temporal lobe (ROI9, hippocampal region) appeared consistently across bands β€” consistent with its established role as the primary seizure onset zone in temporal lobe epilepsy (Engel, 2001).

Important caveat: With only 14 patients, band-specific lateralization patterns could reflect genuine frequency-specific propagation pathways or the specific patients who dominate the High-severity class. These findings should be treated as hypothesis-generating rather than definitive.

Alpha Beta Theta
Alpha band attention topography Beta band attention topography Theta band attention topography

Figure 5. GATv2 attention weights mapped onto brain topography, by frequency band.


6. Does Graph Structure Actually Help? GATv2 vs SVM

Model Alpha AUC Beta AUC Theta AUC
GATv2 ~0.99 ~0.99 ~0.97
SVM (flat wPLI) ~1.00 ~1.00 ~0.89

Both models achieve near-identical AUC. This is the expected and correct result β€” the wPLI connectivity signal itself is discriminative. GATv2's advantage over SVM is interpretability: attention maps identify which ROI connections drive the classification, which SVM cannot provide.

GATv2 vs SVM baseline comparison bar chart across F1, AUC, and balanced accuracy Figure 6. GATv2 vs SVM baseline β€” F1, AUC, and balanced accuracy across all bands.


7. What to Expect When Replicating

Pipeline Step Expected Output Red Flag
Script 02 channel wPLI Theta dominant, mean ~0.6 Values >0.8 = ICA may not have run
Script 05 source wPLI ~25% lower than channel Same values = volume conduction not removed
Script 06 permutation test Observed far right of null distribution Overlap = no real group difference
Script 06 K-Fold AUC >0.95 for alpha <0.7 = check label threshold and class balance
Script 06 LOSO AUC 1.00 in evaluable folds NaN in all folds = all patients one-class (check threshold)
Script 06 attention maps Distributed across multiple ROIs All attention on 1 ROI = increase ATTN_REG from 0.01 to 0.05

πŸ“š Key References

BuzsΓ‘ki, G., & Moser, E. I. (2013). Memory, navigation and theta rhythm in the hippocampal-entorhinal system. Nature Neuroscience, 16(2), 130–138.

Crone, N. E., et al. (2006). High-frequency gamma oscillations and human brain mapping with electrocorticography. Progress in Brain Research, 159, 275–295.

Engel, J. (2001). Mesial temporal lobe epilepsy: what have we learned? The Neuroscientist, 7(4), 340–352.

Jiruska, P., et al. (2013). Synchronization and desynchronization in epilepsy: controversies and hypotheses. Journal of Physiology, 591(4), 787–797.

Klimesch, W. (1999). EEG alpha and theta oscillations reflect cognitive and memory performance. Brain Research Reviews, 29(2–3), 169–195.

Mormann, F., et al. (2000). Mean phase coherence as a measure for phase synchronization and its application to the EEG of epilepsy patients. Clinical Neurophysiology, 111(12), 2218–2237.

Pfurtscheller, G., & Lopes da Silva, F. H. (1999). Event-related EEG/MEG synchronization and desynchronization. Clinical Neurophysiology, 110(11), 1842–1857.

Vinck, M., et al. (2011). An improved index of phase-synchronization for electrophysiological data in the presence of volume-conduction, noise and sample-size bias. NeuroImage, 55(4), 1548–1565.


πŸ—‚οΈ Repository Structure

EpiConnectome/
β”œβ”€β”€ README.md
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ environment.yml                        # Conda environment specification
β”œβ”€β”€ LICENSE
β”œβ”€β”€ EpiConnectome_Tutorial.ipynb           # Step-by-step pipeline walkthrough
β”‚
β”œβ”€β”€ pipeline/
β”‚   β”œβ”€β”€ 01_siena_to_txt_converter.py   # EDF β†’ TXT extraction with annotation timestamps
β”‚   β”œβ”€β”€ 02_channelbasedcode_Siena.py   # Preprocessing Β· ICA Β· Channel-level wPLI Β· circle plots
β”‚   β”œβ”€β”€ 03_siena_feature_extraction.py # EEG feature extraction (SampEn, SpecEn, Var, Skew)
β”‚   β”œβ”€β”€ 04_siencehisto.py              # Connectivity matrix visualizations / histograms
β”‚   β”œβ”€β”€ 05_dspm_connectivity.py        # dSPM source localization Β· 18 ROIs Β· Source wPLI atlas
β”‚   └── 06_gatv2_classification.py     # GATv2 classifier Β· K-Fold Β· LOSO Β· SVM baseline
β”‚
β”œβ”€β”€ results/
β”‚   β”œβ”€β”€ GATv2_Results_v4/              # All GATv2 v4 output figures and metrics
β”‚   β”‚   β”œβ”€β”€ SUMMARY_FIGURE.png
β”‚   β”‚   β”œβ”€β”€ brain_topo_alpha/beta/theta.png
β”‚   β”‚   β”œβ”€β”€ confusion_*.png
β”‚   β”‚   β”œβ”€β”€ roc_*.png
β”‚   β”‚   β”œβ”€β”€ permutation_*.png
β”‚   β”‚   β”œβ”€β”€ heatmap_*.png
β”‚   β”‚   β”œβ”€β”€ gatv2_vs_svm.png
β”‚   β”‚   β”œβ”€β”€ GATv2_metrics.xlsx
β”‚   β”‚   └── subject_severity_report.xlsx
β”‚   β”œβ”€β”€ connectivity_plots/            # Channel-level wPLI circle plots (47 seizures)
β”‚   β”œβ”€β”€ dSPM_Results/                  # Source localization outputs
β”‚   β”œβ”€β”€ Siena_Epilepsy_Channel_analysis_10s/
β”‚   β”œβ”€β”€ Siena_Epilepsy_Feature_Matrices_10s/
β”‚   β”œβ”€β”€ Siena_Epilepsy_Features_10s/
β”‚   β”œβ”€β”€ Siena_Epilepsy_matrices_10s/
β”‚   └── Siena_Epilepsy_quality_control_10s/
β”‚
└── data/
    └── README.md                      # Instructions to download Siena dataset

πŸ”¬ Dataset

Siena Scalp EEG Database β€” publicly available on PhysioNet

Property Value
Source PhysioNet (free, no login)
Citation Detti, P. (2020) Β· doi:10.13026/5d4a-j060
Patients 14 epilepsy subjects
Seizures 47 total
Channels 29 scalp electrodes (10-20 system)
Sample rate 512 Hz
Format EDF + clinical annotations
Size ~13 GB

The data is NOT included in this repository. Download instructions:

wget -r -N -c -np https://physionet.org/files/siena-scalp-eeg/1.0.0/

Or visit: https://physionet.org/content/siena-scalp-eeg/1.0.0/


🧠 Pipeline Overview

Raw EDF Files  →  01: EDF→TXT Conversion  →  02: Preprocessing + Channel wPLI
                                                        ↓
                                          03: EEG Feature Extraction
                                          04: Connectivity Visualizations
                                                        ↓
                                          05: dSPM Source Localization β†’ 18 ROIs
                                                        ↓
                                          06: GATv2 Classification β†’ Severity + Attention Maps

Script Descriptions

Script What it does
01_siena_to_txt_converter.py Reads EDF files, extracts ictal segments (Β±30s) using clinical annotation timestamps
02_channelbasedcode_Siena.py Bandpass filter (4–40 Hz), bad channel detection (LOF), ICA, channel-level wPLI, circle plots, bar charts
03_siena_feature_extraction.py Sample Entropy, Spectral Entropy, Variance, Skewness per channel per band
04_siencehisto.py Histogram and matrix visualizations of connectivity results
05_dspm_connectivity.py dSPM source localization on fsaverage, HCPMMP1 parcellation, 18Γ—18 source wPLI atlas
06_gatv2_classification.py GATv2 graph classifier, 5-fold CV, LOSO, permutation tests, SVM baseline, attention maps

Why wPLI?

Standard coherence is inflated by volume conduction β€” the same cortical source appearing in multiple scalp electrodes. wPLI discards zero-lag interactions, retaining only true brain-to-brain connectivity (Vinck et al., 2011).

Why dSPM?

Scalp electrodes mix signals from many cortical areas. dSPM inverts the EEG forward model to recover source-level signals, giving us 18 anatomically meaningful ROIs instead of 29 scalp positions.

9 Bilateral Cortical Networks (18 ROIs total)

# Network Key for epilepsy?
R1 Prefrontal (ACC + DLPFC)
R2 Motor cortex
R3 Visual cortex (V1 + MT+)
R4 Orbital frontal
R5 Temporal (lateral + ventral)
R6 Superior parietal
R7 Inferior parietal + PCC
R8 Auditory + Insula
R9 Medial Temporal (Hippocampal) ⭐ Primary epilepsy hub

πŸ€– GATv2 Model

Input: 18-node graph (nodes = ROIs, edges = wPLI weights)
Node features: [mean_wPLI, max_wPLI, std_wPLI, ROI_identity (Γ—18), hemispheric_asymmetry]
               β†’ 22-dimensional feature vector per node

GATv2 Layer 1: 16 hidden Γ— 2 heads, ELU activation
               + Attention entropy regularization (Ξ»=0.01)
GATv2 Layer 2: 8 hidden Γ— 2 heads
               + MC Dropout (p=0.5, 50 passes at inference)
Global Mean Pool β†’ 16-dim graph embedding
Classifier: Linear(16β†’32) β†’ ReLU β†’ Dropout β†’ Linear(32β†’2)

Output: High / Low severity label + attention weight per ROI

Key design decisions:

  • Attention regularization (entropy penalty): prevents attention collapse β€” forces the model to attend to multiple ROIs
  • MC Dropout (50 passes): uncertainty estimation on attention weights
  • Balanced classes (50th percentile split): ~20 High / ~20 Low per band β€” prevents trivially zero LOSO F1
  • Dual validation: 5-fold CV (within-subject) + LOSO (cross-subject generalization)
  • SVM baseline: RBF-SVM on flat wPLI features for honest comparison

βš™οΈ Installation

# Clone the repository
git clone https://github.com/duhmariya/EpiConnectome.git
cd EpiConnectome

# Option A: Conda environment (recommended)
conda env create -f environment.yml
conda activate epiconnectome

# Option B: Virtual environment
python -m venv epienv
source epienv/bin/activate  # Windows: epienv\Scripts\activate
pip install -r requirements.txt

Note: For GPU support, install PyTorch with CUDA before running pip install torch-geometric. See PyTorch installation guide.


πŸš€ Usage

Step 1 β€” Download the data

Download the Siena Scalp EEG Database from PhysioNet:

wget -r -N -c -np https://physionet.org/files/siena-scalp-eeg/1.0.0/

Step 2 β€” Update paths

At the top of each script, update the INPUT_DIR and OUTPUT_DIR variables to point to your local data.

Step 3 β€” Run the full pipeline in order

# Step 1: Extract seizure segments from EDF files
python pipeline/01_siena_to_txt_converter.py

# Step 2: Preprocess and compute channel-level wPLI + circle plots
python pipeline/02_channelbasedcode_Siena.py

# Step 3: Extract EEG features (entropy, variance, skewness)
python pipeline/03_siena_feature_extraction.py

# Step 4: Visualize connectivity matrices
python pipeline/04_siencehisto.py

# Step 5: dSPM source localization + source-level wPLI atlas
python pipeline/05_dspm_connectivity.py

# Step 6: GATv2 classification + all results figures
python pipeline/06_gatv2_classification.py

Scripts 01–04 can run independently on channel-level data.
Script 05 requires MNE's fsaverage template (auto-downloaded on first run).
Script 06 requires the output atlas from Script 05.
Expected runtime for Script 06: ~20–40 minutes on CPU, ~5–10 minutes on GPU.

πŸ““ Tutorial Notebook

For a guided walkthrough of the full pipeline with explanations and demo outputs, open:

jupyter notebook EpiConnectome_Tutorial.ipynb

πŸ“ˆ Reproducibility

  • Fixed random seed: RANDOM_SEED = 42 throughout
  • All hyperparameters are defined at the top of each script β€” no hidden configuration files
  • Results in results/ were generated with the exact code in this repository
  • Data source is public and freely available β€” no institutional access required

πŸ—οΈ What's in the Current Version

Fix Description
FIX 1 LOSO AUC now computed only over evaluable folds (both classes present); n_valid/n_total reported explicitly
FIX 2 Permutation test now runs for all bands including combined
FIX 3 Label threshold changed from 75th β†’ 50th percentile (median split) for balanced High/Low classes
FIX 4 LOSO ROC curves only plot folds with valid AUC β€” no misleading NaN lines
FIX 5 Balanced accuracy added to all metric tables (more honest under class imbalance)
FIX 6 SVM baseline added for GATv2 comparison

πŸ“‚ Outputs Generated by Script 06

File Description
SUMMARY_FIGURE.png Classification performance + permutation test significance
confusion_{band}.png K-Fold confusion matrix per band
confusion_{band}_loso.png LOSO confusion matrix per band
roc_{band}.png K-Fold ROC curves per band
roc_{band}_loso.png LOSO ROC curves (valid folds only)
attention_{band}_v4.png Bar chart of ROI attention weights
brain_topo_{band}.png Brain topography of attention weights
heatmap_{band}.png wPLI connectivity Low vs High vs Difference
permutation_{band}.png Permutation test histogram
gatv2_vs_svm.png GATv2 vs SVM comparison
subject_severity_heatmap.png Patient-level wPLI severity overview
GATv2_metrics.xlsx All metrics (K-Fold + LOSO + SVM baseline + Summary)
subject_severity_report.xlsx Per-seizure severity labels and thresholds

πŸ”­ Future Work

  • Clinical ground truth labels (seizure duration, post-ictal duration) as severity proxy
  • Pre-ictal vs ictal connectivity comparison
  • Larger dataset validation (TUH EEG Corpus)
  • Patient-adaptive severity thresholds
  • Graph embedding visualization (t-SNE/UMAP) for subject vs severity separation
  • Multiple comparison correction across frequency bands

πŸ“š Citation

If you use this pipeline in your research, please cite:

@misc{nissar2026epiconnectome,
  author       = {Nissar, Mariya},
  title        = {EpiConnectome: Source-Level Seizure Severity Classification 
                  using Graph Attention Networks},
  year         = {2026},
  publisher    = {GitHub},
  journal      = {GitHub repository},
  howpublished = {\url{https://github.com/duhmariya/EpiConnectome}},
  note         = {Brainhack School 2026}
}

Dataset citation:

Detti, P. (2020). Siena Scalp EEG Database. PhysioNet. https://doi.org/10.13026/5d4a-j060


πŸ“„ License

MIT License β€” see LICENSE for details.


πŸ™ Acknowledgements

  • Brainhack School 2026 organizers and TAs
  • PhysioNet for open data access
  • MNE-Python and PyTorch Geometric communities

EpiConnectome Β· Brainhack School 2026 Β· github.com/duhmariya/EpiConnectome

About

No description, website, or topics provided.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors