{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "intro",
      "metadata": {},
      "source": [
        "# EEG capstone: How robust is the eyes-closed alpha comparison?\n",
        "\n",
        "Reproduce the first browser lab on the same two public recordings. Change the selected time window, then report what the result supports for this participant.\n",
        "\n",
        "Run the cells in order in Jupyter or Colab. This notebook uses Python 3, MNE-Python, NumPy, and Matplotlib. In a fresh notebook environment, install them with `%pip install mne matplotlib`. The first run downloads about 2.5 MB of public EDF files."
      ]
    },
    {
      "cell_type": "code",
      "id": "download",
      "metadata": {},
      "source": [
        "from pathlib import Path\n",
        "from urllib.request import urlretrieve\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "import mne\n",
        "\n",
        "BASE = \"https://physionet.org/files/eegmmidb/1.0.0/S001/\"\n",
        "runs = {\"Eyes open\": \"S001R01.edf\", \"Eyes closed\": \"S001R02.edf\"}\n",
        "data_dir = Path(\"eeg-data\")\n",
        "data_dir.mkdir(exist_ok=True)\n",
        "\n",
        "for filename in runs.values():\n",
        "    target = data_dir / filename\n",
        "    if not target.exists():\n",
        "        temporary = target.with_suffix(\".edf.part\")\n",
        "        urlretrieve(BASE + filename, temporary)\n",
        "        temporary.replace(target)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "trace-notes",
      "metadata": {},
      "source": [
        "## 1. Inspect the excerpts\n",
        "\n",
        "Fp1 is a frontal channel and O1 is an occipital channel. EDF channel labels in this dataset include trailing dots. Subtract the mean of each channel within the displayed segment to match the browser view. The recordings were collected at 160 Hz."
      ]
    },
    {
      "cell_type": "code",
      "id": "traces",
      "metadata": {},
      "source": [
        "def excerpt(condition, start):\n",
        "    raw = mne.io.read_raw_edf(data_dir / runs[condition], preload=True, verbose=\"ERROR\")\n",
        "    return raw.pick([\"Fp1.\", \"O1..\"]).crop(start, start + 4, include_tmax=False)\n",
        "\n",
        "\n",
        "fig, axes = plt.subplots(2, 1, sharex=True, sharey=True, layout=\"constrained\")\n",
        "for condition, axis in zip(runs, axes):\n",
        "    segment = excerpt(condition, 18)\n",
        "    data_uv = segment.get_data(units=\"uV\")\n",
        "    centered = data_uv - data_uv.mean(axis=1, keepdims=True)\n",
        "    for label, samples in zip([\"Fp1\", \"O1\"], centered):\n",
        "        axis.plot(segment.times, samples, label=label)\n",
        "    axis.set(title=condition, ylabel=\"µV\")\n",
        "    axis.legend(loc=\"upper right\")\n",
        "axes[-1].set_xlabel(\"Time in excerpt (s)\")\n",
        "plt.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "spectrum-notes",
      "metadata": {},
      "source": [
        "## 2. Measure relative alpha power\n",
        "\n",
        "Estimate the spectrum of O1 over one four-second segment using a Hann window. Divide summed power in 8–12 Hz by summed power in 4–30 Hz. The browser lab uses the same bands and a symmetric Hann window. MNE’s window convention can produce small differences."
      ]
    },
    {
      "cell_type": "code",
      "id": "spectrum",
      "metadata": {},
      "source": [
        "def alpha_share(condition, start):\n",
        "    segment = excerpt(condition, start).pick([\"O1..\"])\n",
        "    spectrum = segment.compute_psd(\n",
        "        method=\"welch\", fmin=4, fmax=30, n_fft=segment.n_times,\n",
        "        n_per_seg=segment.n_times, n_overlap=0, window=\"hann\",\n",
        "        remove_dc=True, verbose=\"ERROR\",\n",
        "    )\n",
        "    power, frequency = spectrum.get_data(return_freqs=True)\n",
        "    alpha = (frequency >= 8) & (frequency <= 12)\n",
        "    return power[0, alpha].sum() / power[0].sum()\n",
        "\n",
        "\n",
        "for condition in runs:\n",
        "    print(f\"{condition}: {alpha_share(condition, 18):.0%}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "capstone-notes",
      "metadata": {},
      "source": [
        "## 3. Test another time window\n",
        "\n",
        "Compare several start times to see whether the size of the contrast depends on where you look. These excerpts all come from the same participant."
      ]
    },
    {
      "cell_type": "code",
      "id": "capstone",
      "metadata": {},
      "source": [
        "for start in [2, 10, 18, 26]:\n",
        "    opened = alpha_share(\"Eyes open\", start)\n",
        "    closed = alpha_share(\"Eyes closed\", start)\n",
        "    print(f\"{start:2d}–{start + 4:2d} s   open {opened:5.0%}   closed {closed:5.0%}   gap {closed - opened:+.0%}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "reflection",
      "metadata": {},
      "source": [
        "## 4. Write a three-sentence result\n",
        "\n",
        "1. Report both alpha shares at 18 seconds and identify which channel you measured.\n",
        "2. Say whether the direction or size of the contrast changed across excerpts.\n",
        "3. Describe one follow-up you would need before generalizing to other people.\n",
        "\n",
        "At 18 seconds you should get about 31% for eyes open and 71% for eyes closed. These percentages are ratios of spectral power in one channel and band. They do not measure the percentage of brain activity or a person’s level of focus.\n",
        "\n",
        "## Data and credit\n",
        "\n",
        "Gerwin Schalk and colleagues, Wadsworth Center and BCI2000. [EEG Motor Movement/Imagery Dataset v1.0.0](https://physionet.org/content/eegmmidb/1.0.0/) (Schalk, 2009, DOI 10.13026/C28G6P), distributed by PhysioNet under the [Open Data Commons Attribution License v1.0](https://opendatacommons.org/licenses/by/1-0/). See the dataset page for citations to the original BCI2000 paper and PhysioNet."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
