Skip to content

GhadeerMostafa/EEG-MRANC

Repository files navigation

Languages: English | Deutsch | العربية | Türkçe | Français

Multi-Resolution Attention-Guided Neural Cleaner (MRANC)
for Real-World Clinical EEG Denoising

License: CC BY-NC-SA 4.0

Developed by: Ghadeer Mostafa
github.com/GhadeerMostafa/EEG-MRANC


Abstract

MRANC (Multi-Resolution Attention-Guided Neural Cleaner) is a physics-locked deep decomposition framework for 32-channel scalp EEG. The model separates each window into four interpretable artifact stems (EOG, EMG, ECG, baseline noise) plus a recovered neural trace while preserving an exact additive reconstruction identity. Training follows Sequential Knowledge-Stacking: weights are transferred progressively from the SSVEP Artifact Benchmark through DEAP and SEED before parameter-efficient adaptation on CHB-MIT clinical windows. A zero-initialized Multi-Scale Attention Module supplies temporal saliency maps for explainable artifact localization without destabilizing stacked representations at initialization.

This repository ships the complete PyTorch training, evaluation, figure-generation, and manuscript compilation pipeline required to reproduce quantitative benchmarks and the accompanying research report.

What is in this repository?

Included in GitHub Generated or downloaded locally
Model, training, evaluation, plotting, and report scripts Raw EEG files (.dat, .edf, benchmark archives)
docs/ guides and docs/manuscript/ prose and LaTeX template Processed .npy tensors
Empty data and output folder placeholders (.gitkeep) Trained .pth / .pt weights
requirements.txt, LICENSE, artifacts/models/checkpoints/stacking_latest.json critical_figures/, figures/, outputs/reports/
figures/ layout for journal submission assets Word/LaTeX build artifacts

Comprehensive feature map (all commands): FEATURES.md
Full walkthrough: docs/getting-started.md

Model Weights & Evaluation

The repository tracks configuration and weight manifests via stacking_latest.json. The physical .pth binary files are kept local to comply with specific pre-publication and licensing protocols.

To run evaluation scripts, the corresponding .pth files must reside in the paths mapped by stacking_latest.json:

  • Phase 1: artifacts/models/checkpoints/best_mranc_artifact_benchmark_weights_20260530_full.pth
  • Phase 2: artifacts/models/checkpoints/best_mranc_phase2_deap_20260530_full.pth
  • Phase 3: artifacts/models/checkpoints/best_mranc_phase3_seed_20260530_full.pth
  • Phase 4: artifacts/models/weights/mranc_final_attention_20260530_full.pth
  • Baseline: artifacts/models/checkpoints/baseline_eegdenoisenet_20260611_014917.pth

Note for Peer Reviewers: Pre-trained model checkpoints are fully available for review purposes upon request during the journal evaluation phase.

Once weights are in place and processed data exists, run py scripts/evaluate_metrics.py --dataset <name> or py scripts/run_report.py --refresh as described in Core workflow below.

Quick start

git clone https://github.com/GhadeerMostafa/EEG-MRANC.git
cd EEG-MRANC
pip install -r requirements.txt
py src/setup_folders.py
py scripts/check_dependencies.py

CUDA PyTorch on Windows (offline wheels):

.\scripts\install_torch_local.ps1
py -3.12 -c "import torch; print(torch.__version__, torch.cuda.is_available())"

LaTeX / PDF manuscript (pdflatex):

.\scripts\install_latex_local.ps1

See requirements-latex.txt for Linux and macOS install notes.

Core workflow

Run all commands from the repository root. CUDA is required for training and default evaluation.

1. Place raw data       ->  data/raw/{deap,seed,clinical,artifact_benchmark}/
2. Convert / preprocess ->  dataset-specific scripts under scripts/
3. Train (stacking)     ->  py scripts/run_sequential_stacking.py
4. Metrics              ->  py scripts/evaluate_metrics.py --dataset <name>
5. Figures              ->  py scripts/plot_results.py --dataset <name>
6. Report + manuscript  ->  py scripts/run_report.py [--refresh | --full-refresh]

Data preparation

Dataset Raw folder Conversion command Processed output
DEAP data/raw/deap/ py scripts/deap/convert_batch_2.py data/processed/deap/
SEED data/raw/seed/ py scripts/seed/extract_and_convert_seed.py data/processed/seed/
Clinical data/raw/clinical/ py scripts/clinical/download_clinical.py then preprocess_clinical.py data/processed/clinical/
Artifact benchmark data/raw/artifact_benchmark/ bash scripts/download_artifact_benchmark.sh then py scripts/preprocess_artifact_benchmark.py data/processed/artifact_benchmark/

Details: docs/datasets.md

Training (4-phase sequential stacking)

py scripts/run_sequential_stacking.py

Phases: artifact benchmark pretrain, DEAP transfer, SEED transfer, clinical attention adapter. Versioned weights are saved under artifacts/models/checkpoints/ and artifacts/models/weights/; latest paths are recorded in artifacts/models/checkpoints/stacking_latest.json.

Validation benchmarks and report regeneration

Regenerate metrics, figures, Word report, and LaTeX manuscript from existing checkpoints:

py scripts/run_report.py --refresh
py scripts/transform_report.py

Full baseline extraction (retrain stack, baselines, metrics, figures, and report):

py scripts/run_report.py --full-refresh
py scripts/transform_report.py
Output Path
Word report artifacts/reports/clinical/MRANC_Final_Research_Report.docx
LaTeX manuscript (submission) docs/manuscript/MRANC_Final_Research_Report.tex
Figure assets (relative paths) artifacts/figures/manuscript/{dataset}/
LaTeX build copy artifacts/reports/latex/MRANC_Final_Research_Report.tex

Evaluation metrics (standalone)

py scripts/evaluate_metrics.py --dataset clinical
py scripts/evaluate_metrics.py --dataset seed
py scripts/evaluate_metrics.py --dataset deap
py scripts/evaluate_metrics.py --dataset artifact_benchmark

Writes artifacts/reports/{dataset}/evaluation_report_{dataset}.json.

Visualization

py scripts/plot_results.py --dataset clinical
py scripts/run_real_world_pipeline.py --dataset all --window-indices 0 --run-metrics --with-summary-figures --device cuda

Decomposition PNGs are written to artifacts/figures/critical/{dataset}/. Legacy 5-row spatial-RMS plots: add --legacy-spatial-rms to plot_results.py.

Project layout

See PROJECT_STRUCTURE.md for the full v2 map. Summary:

EEG-MRANC/
|-- README.md, FEATURES.md, PROJECT_STRUCTURE.md
|-- src/, scripts/, docs/manuscript/
|-- data/raw/{deap,seed,clinical,artifact_benchmark}/
|-- data/processed/{deap,seed,clinical,artifact_benchmark}/
`-- artifacts/
    |-- models/{checkpoints,weights}/
    |-- figures/{critical,manuscript,legacy}/
    `-- reports/

Upgrade from the old scattered root folders:

py scripts/migrate_project_layout.py --apply

Documentation

Doc Description
FEATURES.md All features and commands
PROJECT_STRUCTURE.md v2 folder layout
docs/getting-started.md Clone to full report
docs/setup.md Python, CUDA, folder setup
docs/datasets.md Raw to processed pipelines
docs/training.md Losses, stacking, checkpoints
docs/commands.md Full CLI reference
docs/clinical.md CHB-MIT download and UDA
docs/figures.md Figures and report workflow

Tensor layout

Processed .npy files: (N_windows, 32, T) float32 (microvolts). Batches: [B, 32, T].

Dataset T Sample rate
DEAP 256 128 Hz
SEED 1000 200 Hz
Clinical 1000 200 Hz
Artifact benchmark 1000 200 Hz

Core modules

Path Role
src/model.py MRANC encoder, attention, decoders
src/dataset.py .npy DataLoader
src/paths.py Project path constants
scripts/train.py Single-dataset training
scripts/run_sequential_stacking.py 4-phase stacking pipeline
scripts/evaluate_metrics.py SNR, PSD, RMSE metrics
scripts/plot_results.py Decomposition figures
scripts/run_real_world_pipeline.py Metrics and figures pipeline
scripts/run_report.py Word research report
scripts/transform_report.py Word to IEEEtran LaTeX export

Windows notes

  • DataLoader defaults to num_workers=0.
  • Run scripts as py scripts/<name>.py from the repo root.
  • Training requires CUDA; CPU fallback is not used by default.

Model outputs — critical figure gallery

The panels below are representative validation-set outputs from the four-phase MRANC stacking pipeline (run_id=20260605_group_splits). Each corpus uses a subject-independent holdout (group-wise splits for DEAP subjects, SEED simulations, and clinical EDF sessions; contiguous temporal holdout for the artifact benchmark). MRANC enforces a physics-locked identity on every window:

pred_eeg = mix − (pred_eog + pred_emg + pred_ecg + pred_basenoise)

Static copies for GitHub are under docs/figures/readme/. Regenerate the full set locally with:

py scripts/run_real_world_pipeline.py --dataset all --window-indices 0 --run-metrics --device cuda
py scripts/generate_interpretability_plots.py --dataset all --window-indices 0 --with-summary

Validation metrics (held-out windows)

Dataset Val windows SNR improvement (dB) PSD corr. (8–30 Hz) Artifact mag. RMSE What MRANC achieved
Clinical (CHB-MIT chb01) 720 −0.03 ± 0.09 0.9999 ± 0.0001 0.037 ± 0.024 Exact reconstruction with near-unity spectral preservation on held-out EDF sessions; physics-only loss (no synthetic artifact labels).
DEAP 9,920 +24.38 ± 4.62 1.000 ± 0.0001 0.019 ± 0.010 Strong supervised stem separation on 4 held-out subjects; large SNR gain while preserving alpha/beta band power.
SEED 32 +0.01 ± 0.04 1.000 ± 0.0000 0.010 ± 0.006 Stable decomposition on held-out simulations with machine-precision reconstruction error.
Artifact benchmark 9 +8.89 ± 0.53 0.963 ± 0.015 0.764 ± 0.196 Physics pretraining on the temporal tail of a continuous SSVEP recording; artifacts isolated without collapsing neural content.

How to read each figure type

Figure type What the model did What to look for
Per-channel decomposition (6 rows) Split the mixed Fp1 trace into cleaned EEG plus four named artifact stems and an attention map. Row 1: raw vs denoised overlay. Rows 2–5: EOG, EMG, ECG, baseline noise stems. Row 6: where the Multi-Scale Attention Block flags contamination.
Denoising fidelity Compare raw input, MRANC output, and (when available) ground-truth clean EEG across Fp1, Cz, and O1, plus spatial-RMS preservation. Denoised traces should track neural morphology without over-flattening; bottom row confirms band-limited energy is retained.
Attention heatmap Overlay mean scalp EEG with normalized attention weights on the same time base. Bright regions should align with visible artifact intervals and co-occur with stem activation in the decomposition panels.

Clinical (CHB-MIT chb01 only) — Fp1, validation window 0

Clinical evaluation uses PhysioNet CHB-MIT patient chb01 only (not TUH or other hospital corpora). MRANC adapted from stacked DEAP/SEED weights using the clinical attention adapter. On held-out EDF sessions the model keeps PSD correlation near 1.0 while routing ocular and muscle energy into interpretable stems rather than a single opaque denoised trace.

Clinical CHB-MIT per-channel decomposition (Fp1, validation window 0)

Figure C1 — Six-row decomposition: raw vs denoised overlay, four artifact stems, and attention weights. EOG energy on Fp1 should dominate during blink-like deflections.

Clinical denoising fidelity across Fp1, Cz, and O1

Figure C2 — Multi-channel fidelity check. MRANC smooths frontal contamination while preserving midline structure needed for clinical review.

Clinical multi-scale attention heatmap

Figure C3 — Temporal saliency aligned with the mixed EEG mean trace; highlights intervals the model treats as artifact-prone.

DEAP — Fp1, validation window 0 (held-out subjects)

Supervised training with reference EOG/EMG/ECG stems yields the strongest quantitative gains in the stacking curriculum.

DEAP per-channel decomposition (Fp1, validation window 0)

Figure D1 — Supervised stem regression on a held-out subject: artifact energy is partitioned into labeled components instead of being discarded blindly.

DEAP denoising fidelity

Figure D2 — Raw vs MRANC denoised traces with ground-truth clean EEG (center column where available).

DEAP attention heatmap

Figure D3 — Attention peaks co-localize with intervals where ocular or muscular stems carry the most energy.

SEED — Fp1, validation window 0 (held-out simulations)

Semi-simulated contamination provides reference artifacts for training; validation uses simulations not seen during training.

SEED per-channel decomposition (Fp1, validation window 0)

Figure S1 — Decomposition on a held-out SEED simulation; reconstruction identity holds to numerical precision.

SEED denoising fidelity

Figure S2 — Denoised output tracks the ground-truth clean trace across frontopolar, central, and occipital derivations.

SEED attention heatmap

Figure S3 — Event-aligned attention on simulated ocular contamination.

Artifact benchmark — Fp1, validation window 0 (temporal holdout)

Phase-1 pretraining on the SSVEP artifact benchmark anchors the physics-locked stems before DEAP/SEED transfer.

Artifact benchmark per-channel decomposition (Fp1, validation window 0)

Figure A1 — Continuous recording split into neural and artifact parts; last 9 windows form the temporal validation tail.

Artifact benchmark denoising fidelity

Figure A2 — Spatial-RMS panel confirms denoising does not remove the underlying oscillatory carrier.

Artifact benchmark attention heatmap

Figure A3 — Attention localization on the benchmark recording used for phase-1 stacking.


License and Academic Usage

Copyright (c) 2026 Ghadeer Mostafa.

This project is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0). See LICENSE.

Non-Commercial: Commercial use or financial exploitation of this software, model weights, manuscript text, or derivative research artifacts is strictly prohibited.

ShareAlike: Any derivative frameworks, modified source code, adapted model architectures, or redistributed research outputs must be distributed under the exact same CC BY-NC-SA 4.0 license terms.

Attribution: Explicit credit must be given to the original creator, Ghadeer Mostafa, with a link to this repository and to the license whenever the work is shared, cited in academic publications, or incorporated into downstream non-commercial research.

About

Official PyTorch implementation of MRANC: A physics-locked, multi-resolution attention-guided neural network for clinical EEG multi-stem artifact removal.

Topics

Resources

License

Stars

2 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors