{ "nbformat_minor": 0, "nbformat": 4, "cells": [ { "execution_count": null, "cell_type": "code", "source": [ "%matplotlib inline" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "\n\nBasic MEG and EEG data processing\n=================================\n\n![](http://mne-tools.github.io/stable/_static/mne_logo.png)\n\n\nMNE-Python reimplements most of MNE-C's (the original MNE command line utils)\nfunctionality and offers transparent scripting.\nOn top of that it extends MNE-C's functionality considerably\n(customize events, compute contrasts, group statistics, time-frequency\nanalysis, EEG-sensor space analyses, etc.) It uses the same files as standard\nMNE unix commands: no need to convert your files to a new system or database.\n\nWhat you can do with MNE Python\n-------------------------------\n\n - **Raw data visualization** to visualize recordings, can also use\n *mne_browse_raw* for extended functionality (see `ch_browse`)\n - **Epoching**: Define epochs, baseline correction, handle conditions etc.\n - **Averaging** to get Evoked data\n - **Compute SSP projectors** to remove ECG and EOG artifacts\n - **Compute ICA** to remove artifacts or select latent sources.\n - **Maxwell filtering** to remove environmental noise.\n - **Boundary Element Modeling**: single and three-layer BEM model\n creation and solution computation.\n - **Forward modeling**: BEM computation and mesh creation\n (see `ch_forward`)\n - **Linear inverse solvers** (dSPM, sLORETA, MNE, LCMV, DICS)\n - **Sparse inverse solvers** (L1/L2 mixed norm MxNE, Gamma Map,\n Time-Frequency MxNE)\n - **Connectivity estimation** in sensor and source space\n - **Visualization of sensor and source space data**\n - **Time-frequency** analysis with Morlet wavelets (induced power,\n intertrial coherence, phase lock value) also in the source space\n - **Spectrum estimation** using multi-taper method\n - **Mixed Source Models** combining cortical and subcortical structures\n - **Dipole Fitting**\n - **Decoding** multivariate pattern analyis of M/EEG topographies\n - **Compute contrasts** between conditions, between sensors, across\n subjects etc.\n - **Non-parametric statistics** in time, space and frequency\n (including cluster-level)\n - **Scripting** (batch and parallel computing)\n\nWhat you're not supposed to do with MNE Python\n----------------------------------------------\n\n - **Brain and head surface segmentation** for use with BEM\n models -- use Freesurfer.\n\n\n

Note

This package is based on the FIF file format from Neuromag. It\n can read and convert CTF, BTI/4D, KIT and various EEG formats to\n FIF.

\n\n\nInstallation of the required materials\n---------------------------------------\n\nSee `install_python_and_mne_python`.\n\n

Note

The expected location for the MNE-sample data is\n ``~/mne_data``. If you downloaded data and an example asks\n you whether to download it again, make sure\n the data reside in the examples directory and you run the script from its\n current directory.\n\n From IPython e.g. say::\n\n cd examples/preprocessing\n\n\n %run plot_find_ecg_artifacts.py

\n\nFrom raw data to evoked data\n----------------------------\n\n\nNow, launch `ipython`_ (Advanced Python shell) using the QT backend, which\nis best supported across systems::\n\n $ ipython --matplotlib=qt\n\nFirst, load the mne package:\n\n

Note

In IPython, you can press **shift-enter** with a given cell\n selected to execute it and advance to the next cell:

\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "import mne" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "If you'd like to turn information status messages off:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mne.set_log_level('WARNING')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "But it's generally a good idea to leave them on:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mne.set_log_level('INFO')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "You can set the default level by setting the environment variable\n\"MNE_LOGGING_LEVEL\", or by having mne-python write preferences to a file:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mne.set_config('MNE_LOGGING_LEVEL', 'WARNING', set_env=True)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Note that the location of the mne-python preferences file (for easier manual\nediting) can be found using:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mne.get_config_path()" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "By default logging messages print to the console, but look at\n:func:`mne.set_log_file` to save output to a file.\n\nAccess raw data\n^^^^^^^^^^^^^^^\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "from mne.datasets import sample # noqa\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nprint(raw_fname)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "

Note

The MNE sample dataset should be downloaded automatically but be\n patient (approx. 2GB)

\n\nRead data from file:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "raw = mne.io.read_raw_fif(raw_fname)\nprint(raw)\nprint(raw.info)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Look at the channels in raw:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "print(raw.ch_names)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Read and plot a segment of raw data\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "start, stop = raw.time_as_index([100, 115]) # 100 s to 115 s data segment\ndata, times = raw[:, start:stop]\nprint(data.shape)\nprint(times.shape)\ndata, times = raw[2:20:3, start:stop] # access underlying data\nraw.plot()" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Save a segment of 150s of raw data (MEG only):\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True,\n exclude='bads')\nraw.save('sample_audvis_meg_raw.fif', tmin=0, tmax=150, picks=picks,\n overwrite=True)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Define and read epochs\n^^^^^^^^^^^^^^^^^^^^^^\n\nFirst extract events:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "events = mne.find_events(raw, stim_channel='STI 014')\nprint(events[:5])" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Note that, by default, we use stim_channel='STI 014'. If you have a different\nsystem (e.g., a newer system that uses channel 'STI101' by default), you can\nuse the following to set the default stim channel to use for finding events:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mne.set_config('MNE_STIM_CHANNEL', 'STI101', set_env=True)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Events are stored as a 2D numpy array where the first column is the time\ninstant and the last one is the event number. It is therefore easy to\nmanipulate.\n\nDefine epochs parameters:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "event_id = dict(aud_l=1, aud_r=2) # event trigger and conditions\ntmin = -0.2 # start of each epoch (200ms before the trigger)\ntmax = 0.5 # end of each epoch (500ms after the trigger)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Exclude some channels (original bads + 2 more):\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "raw.info['bads'] += ['MEG 2443', 'EEG 053']" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "The variable raw.info['bads'] is just a python list.\n\nPick the good channels, excluding raw.info['bads']:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "picks = mne.pick_types(raw.info, meg=True, eeg=True, eog=True, stim=False,\n exclude='bads')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Alternatively one can restrict to magnetometers or gradiometers with:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "mag_picks = mne.pick_types(raw.info, meg='mag', eog=True, exclude='bads')\ngrad_picks = mne.pick_types(raw.info, meg='grad', eog=True, exclude='bads')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Define the baseline period:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "baseline = (None, 0) # means from the first instant to t = 0" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Define peak-to-peak rejection parameters for gradiometers, magnetometers\nand EOG:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Read epochs:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,\n baseline=baseline, preload=False, reject=reject)\nprint(epochs)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Get single epochs for one condition:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "epochs_data = epochs['aud_l'].get_data()\nprint(epochs_data.shape)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "epochs_data is a 3D array of dimension (55 epochs, 365 channels, 106 time\ninstants).\n\nScipy supports read and write of matlab files. You can save your single\ntrials with:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "from scipy import io # noqa\nio.savemat('epochs_data.mat', dict(epochs_data=epochs_data), oned_as='row')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "or if you want to keep all the information about the data you can save your\nepochs in a fif file:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "epochs.save('sample-epo.fif')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "and read them later with:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "saved_epochs = mne.read_epochs('sample-epo.fif')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Compute evoked responses for auditory responses by averaging and plot it:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "evoked = epochs['aud_l'].average()\nprint(evoked)\nevoked.plot()" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ ".. topic:: Exercise\n\n 1. Extract the max value of each epoch\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "max_in_each_epoch = [e.max() for e in epochs['aud_l']] # doctest:+ELLIPSIS\nprint(max_in_each_epoch[:4]) # doctest:+ELLIPSIS" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "It is also possible to read evoked data stored in a fif file:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'\nevoked1 = mne.read_evokeds(\n evoked_fname, condition='Left Auditory', baseline=(None, 0), proj=True)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Or another one stored in the same file:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "evoked2 = mne.read_evokeds(\n evoked_fname, condition='Right Auditory', baseline=(None, 0), proj=True)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Two evoked objects can be contrasted using :func:`mne.combine_evoked`.\nThis function can use ``weights='equal'``, which provides a simple\nelement-by-element subtraction (and sets the\n``mne.Evoked.nave`` attribute properly based on the underlying number\nof trials) using either equivalent call:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "contrast = mne.combine_evoked([evoked1, evoked2], weights=[0.5, -0.5])\ncontrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')\nprint(contrast)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "To do a weighted sum based on the number of averages, which will give\nyou what you would have gotten from pooling all trials together in\n:class:`mne.Epochs` before creating the :class:`mne.Evoked` instance,\nyou can use ``weights='nave'``:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "average = mne.combine_evoked([evoked1, evoked2], weights='nave')\nprint(contrast)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Instead of dealing with mismatches in the number of averages, we can use\ntrial-count equalization before computing a contrast, which can have some\nbenefits in inverse imaging (note that here ``weights='nave'`` will\ngive the same result as ``weights='equal'``):\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "epochs_eq = epochs.copy().equalize_event_counts(['aud_l', 'aud_r'])[0]\nevoked1, evoked2 = epochs_eq['aud_l'].average(), epochs_eq['aud_r'].average()\nprint(evoked1)\nprint(evoked2)\ncontrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')\nprint(contrast)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Time-Frequency: Induced power and inter trial coherence\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nDefine parameters:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "import numpy as np # noqa\nn_cycles = 2 # number of cycles in Morlet wavelet\nfreqs = np.arange(7, 30, 3) # frequencies of interest" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Compute induced power and phase-locking values and plot gradiometers:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "from mne.time_frequency import tfr_morlet # noqa\npower, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles,\n return_itc=True, decim=3, n_jobs=1)\npower.plot([power.ch_names.index('MEG 1332')])" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Inverse modeling: MNE and dSPM on evoked and raw data\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nImport the required functions:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "from mne.minimum_norm import apply_inverse, read_inverse_operator # noqa" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Read the inverse operator:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'\ninverse_operator = read_inverse_operator(fname_inv)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Define the inverse parameters:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "snr = 3.0\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\"" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Compute the inverse solution:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "stc = apply_inverse(evoked, inverse_operator, lambda2, method)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Save the source time courses to disk:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "stc.save('mne_dSPM_inverse')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Now, let's compute dSPM on a raw file within a label:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "fname_label = data_path + '/MEG/sample/labels/Aud-lh.label'\nlabel = mne.read_label(fname_label)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Compute inverse solution during the first 15s:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "from mne.minimum_norm import apply_inverse_raw # noqa\nstart, stop = raw.time_as_index([0, 15]) # read the first 15s of data\nstc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,\n start, stop)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Save result in stc files:\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "stc.save('mne_dSPM_raw_inverse_Aud')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "What else can you do?\n^^^^^^^^^^^^^^^^^^^^^\n\n - detect heart beat QRS component\n - detect eye blinks and EOG artifacts\n - compute SSP projections to remove ECG or EOG artifacts\n - compute Independent Component Analysis (ICA) to remove artifacts or\n select latent sources\n - estimate noise covariance matrix from Raw and Epochs\n - visualize cross-trial response dynamics using epochs images\n - compute forward solutions\n - estimate power in the source space\n - estimate connectivity in sensor and source space\n - morph stc from one brain to another for group studies\n - compute mass univariate statistics base on custom contrasts\n - visualize source estimates\n - export raw, epochs, and evoked data to other python data analysis\n libraries e.g. pandas\n - and many more things ...\n\nWant to know more ?\n^^^^^^^^^^^^^^^^^^^\n\nBrowse `the examples gallery `_.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "print(\"Done!\")" ], "outputs": [], "metadata": { "collapsed": false } } ], "metadata": { "kernelspec": { "display_name": "Python 2", "name": "python2", "language": "python" }, "language_info": { "mimetype": "text/x-python", "nbconvert_exporter": "python", "name": "python", "file_extension": ".py", "version": "2.7.13", "pygments_lexer": "ipython2", "codemirror_mode": { "version": 2, "name": "ipython" } } } }