{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# 01. Detect HFOs in Simulated Dataset\n\n.. currentmodule:: mne_hfo\n\nMNE-HFO currently depends on the data structures defined by ``MNE-Python``.\nNamely the :py:class:`mne.io.Raw` object.\n\nIn this example, we use MNE-HFO to simulate raw data and detect HFOs.\nSpecifically, we will follow these steps:\n\n1. Create some simulated data and artificially simulate a few HFOs\n\n2. Run a few ``mne_hfo.base.Detector`` instances to detect HFOs\n\n3. Format the detected HFOs as a :class:`pandas.DataFrame`\n\n4. Write to disk and read it in again.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: Adam Li <adam2392@gmail.com>\n#"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We are importing everything we need for this example:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom mne import create_info\nfrom mne.io import RawArray\n\nfrom mne_hfo import (RMSDetector, compute_chs_hfo_rates,\n                     events_to_annotations)\nfrom mne_hfo.simulate import simulate_hfo"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Simulate the data\n\nFirst, we need some data to work with. We will use a fake dataset that we\nsimulate.\n\nIn this example, we will simulate sinusoidal data that has an artificial\nHFO added at two points with 9 cycles each.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# simulate the testing dataset\nfreqs = [2.5, 6.0, 10.0, 16.0, 32.5, 67.5, 165.0,\n         250.0, 425.0, 500.0, 800.0, 1500.0]\n\n# sampling frequency\nsfreq = 2000\n\n# number of seconds to simulate\nn = sfreq * 10\ndata = np.zeros(n)\n\n# generate some sinusoidal data at specified frequencies\nx = np.arange(n)\nfor freq in freqs:\n    # freq_amp = basic_amp / freq\n    y = np.sin(2 * np.pi * freq * x / sfreq)\n    data += y\n\n# We have dummy data now inject 2 HFOs\nfreq = 250\nnumcycles = 9\nsim = simulate_hfo(sfreq, freq, numcycles)[0]\nev_start = sfreq\ndata[ev_start: ev_start + len(sim)] += sim * 10\n\nsim = simulate_hfo(sfreq, freq, numcycles)[0]\nev_start = 7 * sfreq\ndata[ev_start: ev_start + len(sim)] += sim * 10\n\n# convert the data into mne-python\n# note: the channel names are made up and the channel types are just\n# set to 'seeg' for the sake of the example\nch_names = ['A1']\ninfo = create_info(sfreq=sfreq, ch_names=ch_names, ch_types='seeg')\nraw = RawArray(data=data[np.newaxis, :], info=info)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's plot the data and see what it looks like\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "raw.plot()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Detect HFOs\nAll detectors inherit from the base class ``mne_hfo.base.Detector``,\nwhich inherits from the :class:`sklearn.base.BaseEstimator` class.\nTo run any estimator, one instantiates it along with the hyper-parameters,\nand then calls the ``fit`` function. Afterwards, detected HFOs are available\nin the various data structures. The recommended usage is the DataFrame, which\nis accessible via the ``mne_hfo.base.Detector.hfo_df`` property.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "kwargs = {\n    'threshold': 3,  # threshold for \"significance\"\n    'win_size': 100,  # window size in samples\n    'overlap': 0.25  # overlap in percentage relative to the window size\n}\ndetector = RMSDetector(**kwargs)\n\n# run detector\ndetector.fit(X=raw)\n\n# get the event dataframe\nevent_df = detector.hfo_event_df\nprint(event_df.head())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Convert HFO events to annotations\nDetectors output HFO events detected as a DataFrame fashioned after the\n``*_events.tsv`` files in BIDS-iEEG. Instead, HFO events are indeed\nDerivatives of the Raw data, that are estimated/detected using mne-hfo.\nThe correct way to store them is in terms of an ``*_annotations.tsv``,\naccording to the BIDS-Derivatives specification.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# convert event df -> annotation df\nannot_df = events_to_annotations(event_df)\nprint(annot_df.head())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "compute HFO rate as HFOs per second\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ch_rates = compute_chs_hfo_rates(annot_df=annot_df, rate='s')\nprint(ch_rates)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}