{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e472aba0",
   "metadata": {},
   "source": [
    "# Motor imagery and benchmarking with MOABB\n",
    "\n",
    "This notebook follows the NeuroTechX Learn lab on motor imagery. You will:\n",
    "\n",
    "1. Load imagined left and right fist trials from the PhysioNet EEG Motor Movement/Imagery dataset with MNE-Python.\n",
    "2. Score two standard pipelines with cross-validation: CSP + LDA, and a Riemannian tangent-space pipeline from pyRiemann.\n",
    "3. Compare within-subject and cross-subject accuracy, and compare both with chance level.\n",
    "4. Run the same pipelines through MOABB's `WithinSessionEvaluation` on the BNCI 2014-001 dataset.\n",
    "\n",
    "**Setup.** Python 3.10 or later. Install the packages once:\n",
    "\n",
    "```\n",
    "pip install mne scikit-learn pyriemann moabb matplotlib\n",
    "```\n",
    "\n",
    "**Data.** Part 1 downloads about 75 MB (subjects 1 to 10, runs 4, 8 and 12). Part 4 downloads about 170 MB (BNCI 2014-001, subjects 1 and 2). Files are cached in `~/mne_data`.\n",
    "\n",
    "**Credits and licences.** PhysioNet EEG Motor Movement/Imagery Dataset v1.0.0, ODC-By 1.0: Schalk et al. (2004), *IEEE Trans. Biomed. Eng.* 51(6):1034-1043, and Goldberger et al. (2000), *Circulation* 101(23):e215-e220. BNCI 2014-001 (BCI Competition IV, dataset 2a): Tangermann et al. (2012), *Front. Neurosci.* 6:55. MOABB: Jayaram and Barachant (2018), *J. Neural Eng.* 15(6):066011; https://github.com/NeuroTechX/moabb."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7203a54",
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import mne\n",
    "import numpy as np\n",
    "from mne.datasets import eegbci\n",
    "from mne.decoding import CSP\n",
    "from pyriemann.estimation import Covariances\n",
    "from pyriemann.tangentspace import TangentSpace\n",
    "from scipy.stats import binom\n",
    "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.model_selection import LeaveOneGroupOut, StratifiedKFold, cross_val_score, permutation_test_score\n",
    "from sklearn.pipeline import make_pipeline\n",
    "\n",
    "mne.set_log_level(\"ERROR\")\n",
    "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n",
    "print(\"MNE\", mne.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8470901",
   "metadata": {},
   "source": [
    "## 1. Load the imagery trials\n",
    "\n",
    "In runs 4, 8 and 12, a target on the screen cues the participant to imagine opening and closing the left fist (`T1`) or the right fist (`T2`) for about 4 s. We re-reference to the common average, band-pass 8 to 30 Hz to keep the mu and beta rhythms, and keep 0.5 to 2.5 s after each cue. These are the same choices as the browser lab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43b3d2cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "SUBJECTS = range(1, 11)\n",
    "RUNS = [4, 8, 12]\n",
    "\n",
    "\n",
    "def load_subject(subject):\n",
    "    files = eegbci.load_data(subject, RUNS, update_path=False)\n",
    "    raw = mne.concatenate_raws([mne.io.read_raw_edf(f, preload=True) for f in files])\n",
    "    eegbci.standardize(raw)\n",
    "    raw.set_eeg_reference(\"average\", projection=False)\n",
    "    raw.filter(8.0, 30.0)\n",
    "    events, _ = mne.events_from_annotations(raw, event_id=dict(T1=0, T2=1))\n",
    "    epochs = mne.Epochs(raw, events, dict(left=0, right=1), tmin=0.5, tmax=2.5, baseline=None, preload=True)\n",
    "    return epochs.get_data(copy=False), epochs.events[:, 2]\n",
    "\n",
    "\n",
    "data = {subject: load_subject(subject) for subject in SUBJECTS}\n",
    "X1, y1 = data[1]\n",
    "print(\"Subject 1:\", X1.shape, \"(trials, channels, samples);\", np.bincount(y1), \"trials per class\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77c865b2",
   "metadata": {},
   "source": [
    "## 2. Two pipelines, scored with cross-validation\n",
    "\n",
    "- **CSP + LDA.** Common spatial patterns learn spatial filters whose output variance differs most between the two classes. The log-variance of each filtered signal is the feature, and linear discriminant analysis classifies it.\n",
    "- **Tangent space + logistic regression.** Each trial's spatial covariance matrix is a point on a curved space of symmetric positive-definite matrices. pyRiemann projects those points onto a flat tangent space, where a linear classifier works well (Barachant et al., 2012).\n",
    "\n",
    "Every step that learns from data sits inside the pipeline, so cross-validation refits it on each training fold. Fitting CSP on all trials before splitting would leak the test labels into the features."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e3a349e",
   "metadata": {},
   "outputs": [],
   "source": [
    "pipelines = {\n",
    "    \"CSP+LDA\": make_pipeline(CSP(n_components=6, log=True), LinearDiscriminantAnalysis()),\n",
    "    \"TS+LR\": make_pipeline(Covariances(\"oas\"), TangentSpace(metric=\"riemann\"), LogisticRegression(max_iter=1000)),\n",
    "}\n",
    "cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
    "\n",
    "within = {name: [] for name in pipelines}\n",
    "for subject, (X, y) in data.items():\n",
    "    for name, pipeline in pipelines.items():\n",
    "        within[name].append(cross_val_score(pipeline, X, y, cv=cv).mean())\n",
    "\n",
    "print(\"subject  \" + \"  \".join(f\"{name:>8}\" for name in pipelines))\n",
    "for i, subject in enumerate(SUBJECTS):\n",
    "    print(f\"S{subject:03d}     \" + \"  \".join(f\"{within[name][i]:8.2f}\" for name in pipelines))\n",
    "print(\"mean     \" + \"  \".join(f\"{np.mean(within[name]):8.2f}\" for name in pipelines))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29baba3c",
   "metadata": {},
   "source": [
    "## 3. Is that better than chance?\n",
    "\n",
    "With two balanced classes, guessing gives 50% on average. With only 45 trials, a classifier with no real information can still score well above 50% by luck. The binomial distribution gives the accuracy that pure guessing exceeds only 5% of the time (Combrisson and Jerbi, 2015). A permutation test asks the same question empirically: shuffle the labels, rerun the whole cross-validation, and see how often the shuffled score matches the real one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "018bd38a",
   "metadata": {},
   "outputs": [],
   "source": [
    "n_trials = len(y1)\n",
    "threshold = binom.ppf(0.95, n_trials, 0.5) / n_trials\n",
    "print(f\"With {n_trials} trials, guessing exceeds {threshold:.0%} only 5% of the time.\")\n",
    "for name in pipelines:\n",
    "    above = sum(score > threshold for score in within[name])\n",
    "    print(f\"{name}: {above} of {len(within[name])} subjects above that threshold\")\n",
    "\n",
    "score, permuted, p_value = permutation_test_score(pipelines[\"CSP+LDA\"], *data[7], cv=cv, n_permutations=100, random_state=0)\n",
    "print(f\"\\nSubject 7, CSP+LDA: accuracy {score:.2f}, shuffled-label mean {permuted.mean():.2f}, p = {p_value:.3f}\")\n",
    "plt.hist(permuted, bins=20, color=\"0.6\")\n",
    "plt.axvline(score, color=\"C3\", label=\"real labels\")\n",
    "plt.xlabel(\"cross-validated accuracy\")\n",
    "plt.ylabel(\"permutations\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6549eb40",
   "metadata": {},
   "source": [
    "## 4. Within-subject versus cross-subject\n",
    "\n",
    "Within-subject scores train and test on the same person. A cross-subject score trains on nine people and tests on the tenth (leave-one-subject-out). It answers a different question: does the model work for someone it has never seen?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4a39aa9",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_all = np.concatenate([data[s][0] for s in SUBJECTS])\n",
    "y_all = np.concatenate([data[s][1] for s in SUBJECTS])\n",
    "groups = np.concatenate([[s] * len(data[s][1]) for s in SUBJECTS])\n",
    "\n",
    "for name, pipeline in pipelines.items():\n",
    "    scores = cross_val_score(pipeline, X_all, y_all, groups=groups, cv=LeaveOneGroupOut())\n",
    "    print(f\"{name}: within-subject mean {np.mean(within[name]):.2f}, cross-subject mean {scores.mean():.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8610bfe3",
   "metadata": {},
   "source": [
    "## 5. The same comparison with MOABB\n",
    "\n",
    "[MOABB](https://github.com/NeuroTechX/moabb) (Mother of All BCI Benchmarks) is a NeuroTechX project that standardizes this work: it downloads public datasets, applies a paradigm's preprocessing, and runs every pipeline under the same evaluation. See the [documentation](https://moabb.neurotechx.com/docs/).\n",
    "\n",
    "Here we use BNCI 2014-001 (BCI Competition IV, dataset 2a): 22 EEG channels at 250 Hz, four imagery classes, two sessions per person. The `LeftRightImagery` paradigm keeps left and right hand trials. `WithinSessionEvaluation` runs 5-fold cross-validation inside each session and reports ROC AUC for two-class problems. Two subjects keep the download small."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38cbde0f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from moabb.datasets import BNCI2014_001\n",
    "from moabb.evaluations import WithinSessionEvaluation\n",
    "from moabb.paradigms import LeftRightImagery\n",
    "\n",
    "moabb_pipelines = {\n",
    "    \"CSP+LDA\": make_pipeline(CSP(n_components=6, log=True), LinearDiscriminantAnalysis()),\n",
    "    \"TS+LR\": make_pipeline(Covariances(\"oas\"), TangentSpace(metric=\"riemann\"), LogisticRegression(max_iter=1000)),\n",
    "}\n",
    "dataset = BNCI2014_001()\n",
    "dataset.subject_list = [1, 2]\n",
    "evaluation = WithinSessionEvaluation(paradigm=LeftRightImagery(), datasets=[dataset], overwrite=True, hdf5_path=None)\n",
    "results = evaluation.process(moabb_pipelines)\n",
    "print(results.pivot_table(index=[\"subject\", \"session\"], columns=\"pipeline\", values=\"score\").round(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ef7e3a5",
   "metadata": {},
   "source": [
    "## Questions to answer\n",
    "\n",
    "1. How many of the ten PhysioNet subjects score above the binomial threshold? What would you report for the others?\n",
    "2. Why does cross-subject accuracy drop? Name two things that differ between people.\n",
    "3. MOABB reports ROC AUC, not accuracy. When is AUC the better choice?\n",
    "4. Change `tmin` and `tmax` in `load_subject`, or the band in `raw.filter`. If you try many settings and report the best one, what happens to the meaning of the score?\n",
    "\n",
    "## References\n",
    "\n",
    "- Barachant, A., Bonnet, S., Congedo, M., and Jutten, C. (2012). Multiclass brain-computer interface classification by Riemannian geometry. *IEEE Trans. Biomed. Eng.* 59(4):920-928.\n",
    "- Combrisson, E., and Jerbi, K. (2015). Exceeding chance level by chance: The caveat of theoretical chance levels in brain signal classification and statistical assessment of decoding accuracy. *J. Neurosci. Methods* 250:126-136.\n",
    "- Goldberger, A. L., et al. (2000). PhysioBank, PhysioToolkit, and PhysioNet. *Circulation* 101(23):e215-e220.\n",
    "- Jayaram, V., and Barachant, A. (2018). MOABB: trustworthy algorithm benchmarking for BCIs. *J. Neural Eng.* 15(6):066011.\n",
    "- Pfurtscheller, G., and Lopes da Silva, F. H. (1999). Event-related EEG/MEG synchronization and desynchronization: basic principles. *Clin. Neurophysiol.* 110(11):1842-1857.\n",
    "- Schalk, G., McFarland, D. J., Hinterberger, T., Birbaumer, N., and Wolpaw, J. R. (2004). BCI2000: a general-purpose brain-computer interface (BCI) system. *IEEE Trans. Biomed. Eng.* 51(6):1034-1043.\n",
    "- Tangermann, M., et al. (2012). Review of the BCI Competition IV. *Front. Neurosci.* 6:55."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
