{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Demonstrate impact of whitening on source estimates\n\n\nThis example demonstrates the relationship between the noise covariance\nestimate and the MNE / dSPM source amplitudes. It computes source estimates for\nthe SPM faces data and compares proper regularization with insufficient\nregularization based on the methods described in _. The example demonstrates\nthat improper regularization can lead to overestimation of source amplitudes.\nThis example makes use of the previous, non-optimized code path that was used\nbefore implementing the suggestions presented in _.\n\nThis example does quite a bit of processing, so even on a\nfast machine it can take a couple of minutes to complete.\n\n

#### Warning

Please do not copy the patterns presented here for your own\n analysis, this is example is purely illustrative.

\n\nReferences\n----------\n..  Engemann D. and Gramfort A. (2015) Automated model selection in\n covariance estimation and spatial whitening of MEG and EEG signals,\n vol. 108, 328-342, NeuroImage.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Author: Denis A. Engemann \n#\n# License: BSD (3-clause)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne import io\nfrom mne.datasets import spm_face\nfrom mne.minimum_norm import apply_inverse, make_inverse_operator\nfrom mne.cov import compute_covariance\n\nprint(__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Get data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data_path = spm_face.data_path()\nsubjects_dir = data_path + '/subjects'\n\nraw_fname = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces%d_3D.ds'\n\nraw = io.read_raw_ctf(raw_fname % 1) # Take first run\n# To save time and memory for this demo, we'll just use the first\n# 2.5 minutes (all we need to get 30 total events) and heavily\n# resample 480->60 Hz (usually you wouldn't do either of these!)\nraw = raw.crop(0, 150.).load_data()\n\npicks = mne.pick_types(raw.info, meg=True, exclude='bads')\nraw.filter(None, 20.)\n\nevents = mne.find_events(raw, stim_channel='UPPT001')\n\nevent_ids = {\"faces\": 1, \"scrambled\": 2}\ntmin, tmax = -0.2, 0.5\nbaseline = (None, 0)\nreject = dict(mag=3e-12)\n\n# Make forward\ntrans = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces1_3D_raw-trans.fif'\nsrc = data_path + '/subjects/spm/bem/spm-oct-6-src.fif'\nbem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif'\nforward = mne.make_forward_solution(raw.info, trans, src, bem)\ndel src\n\n# inverse parameters\nconditions = 'faces', 'scrambled'\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\nclim = dict(kind='value', lims=[0, 2.5, 5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Estimate covariances\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "samples_epochs = 5, 15,\nmethod = 'empirical', 'shrunk'\ncolors = 'steelblue', 'red'\n\nevokeds = list()\nstcs = list()\nmethods_ordered = list()\nfor n_train in samples_epochs:\n # estimate covs based on a subset of samples\n # make sure we have the same number of conditions.\n events_ = np.concatenate([events[events[:, 2] == id_][:n_train]\n for id_ in [event_ids[k] for k in conditions]])\n events_ = events_[np.argsort(events_[:, 0])]\n epochs_train = mne.Epochs(raw, events_, event_ids, tmin, tmax, picks=picks,\n baseline=baseline, preload=True, reject=reject,\n decim=8)\n epochs_train.equalize_event_counts(event_ids)\n assert len(epochs_train) == 2 * n_train\n\n # We know some of these have too few samples, so suppress warning\n # with verbose='error'\n noise_covs = compute_covariance(\n epochs_train, method=method, tmin=None, tmax=0, # baseline only\n return_estimators=True, rank=None, verbose='error') # returns list\n # prepare contrast\n evokeds = [epochs_train[k].average() for k in conditions]\n del epochs_train, events_\n # do contrast\n\n # We skip empirical rank estimation that we introduced in response to\n # the findings in reference  to use the naive code path that\n # triggered the behavior described in . The expected true rank is\n # 274 for this dataset. Please do not do this with your data but\n # rely on the default rank estimator that helps regularizing the\n # covariance.\n stcs.append(list())\n methods_ordered.append(list())\n for cov in noise_covs:\n inverse_operator = make_inverse_operator(evokeds.info, forward,\n cov, loose=0.2, depth=0.8)\n assert len(inverse_operator['sing']) == 274 # sanity check\n stc_a, stc_b = (apply_inverse(e, inverse_operator, lambda2, \"dSPM\",\n pick_ori=None) for e in evokeds)\n stc = stc_a - stc_b\n methods_ordered[-1].append(cov['method'])\n stcs[-1].append(stc)\n del inverse_operator, evokeds, cov, noise_covs, stc, stc_a, stc_b\ndel raw, forward # save some memory" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show the resulting source estimates\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, (axes1, axes2) = plt.subplots(2, 3, figsize=(9.5, 5))\n\nfor ni, (n_train, axes) in enumerate(zip(samples_epochs, (axes1, axes2))):\n # compute stc based on worst and best\n ax_dynamics = axes\n for stc, ax, method, kind, color in zip(stcs[ni],\n axes[::2],\n methods_ordered[ni],\n ['best', 'worst'],\n colors):\n brain = stc.plot(subjects_dir=subjects_dir, hemi='both', clim=clim,\n initial_time=0.175, background='w', foreground='k')\n brain.show_view('ven')\n im = brain.screenshot()\n brain.close()\n\n ax.axis('off')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.imshow(im)\n ax.set_title('{0} ({1} epochs)'.format(kind, n_train * 2))\n\n # plot spatial mean\n stc_mean = stc.data.mean(0)\n ax_dynamics.plot(stc.times * 1e3, stc_mean,\n label='{0} ({1})'.format(method, kind),\n color=color)\n # plot spatial std\n stc_var = stc.data.std(0)\n ax_dynamics.fill_between(stc.times * 1e3, stc_mean - stc_var,\n stc_mean + stc_var, alpha=0.2, color=color)\n\n # signal dynamics worst and best\n ax_dynamics.set(title='{0} epochs'.format(n_train * 2),\n xlabel='Time (ms)', ylabel='Source Activation (dSPM)',\n xlim=(tmin * 1e3, tmax * 1e3), ylim=(-3, 3))\n ax_dynamics.legend(loc='upper left', fontsize=10)\n\nfig.subplots_adjust(hspace=0.2, left=0.01, right=0.99, wspace=0.03)" ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 0 }