{ "nbformat_minor": 0, "nbformat": 4, "cells": [ { "execution_count": null, "cell_type": "code", "source": [ "%matplotlib inline" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "\n\n# Repeated measures ANOVA on source data with spatio-temporal clustering\n\n\nThis example illustrates how to make use of the clustering functions\nfor arbitrary, self-defined contrasts beyond standard t-tests. In this\ncase we will tests if the differences in evoked responses between\nstimulation modality (visual VS auditory) depend on the stimulus\nlocation (left vs right) for a group of subjects (simulated here\nusing one subject's data). For this purpose we will compute an\ninteraction effect using a repeated measures ANOVA. The multiple\ncomparisons problem is addressed with a cluster-level permutation test\nacross space and time.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "# Authors: Alexandre Gramfort \n# Eric Larson \n# Denis Engemannn \n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport numpy as np\nfrom numpy.random import randn\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne import (io, spatial_tris_connectivity, compute_morph_matrix,\n grade_to_tris)\nfrom mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,\n f_mway_rm, summarize_clusters_stc)\n\nfrom mne.minimum_norm import apply_inverse, read_inverse_operator\nfrom mne.datasets import sample\n\nprint(__doc__)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Set parameters\n--------------\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "data_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nevent_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\nsubjects_dir = data_path + '/subjects'\n\ntmin = -0.2\ntmax = 0.3 # Use a lower tmax to reduce multiple comparisons\n\n# Setup for reading the raw data\nraw = io.read_raw_fif(raw_fname)\nevents = mne.read_events(event_fname)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Read epochs for all channels, removing a bad one\n------------------------------------------------\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "raw.info['bads'] += ['MEG 2443']\npicks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads')\n# we'll load all four conditions that make up the 'two ways' of our ANOVA\n\nevent_id = dict(l_aud=1, r_aud=2, l_vis=3, r_vis=4)\nreject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=reject, preload=True)\n\n# Equalize trial counts to eliminate bias (which would otherwise be\n# introduced by the abs() performed below)\nepochs.equalize_event_counts(event_id)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Transform to source space\n-------------------------\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'\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\ninverse_operator = read_inverse_operator(fname_inv)\n\n# we'll only use one hemisphere to speed up this example\n# instead of a second vertex array we'll pass an empty array\nsample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)]\n\n# Let's average and compute inverse, then resample to speed things up\nconditions = []\nfor cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']: # order is important\n evoked = epochs[cond].average()\n evoked.resample(50, npad='auto')\n condition = apply_inverse(evoked, inverse_operator, lambda2, method)\n # Let's only deal with t > 0, cropping to reduce multiple comparisons\n condition.crop(0, None)\n conditions.append(condition)\n\ntmin = conditions[0].tmin\ntstep = conditions[0].tstep" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Transform to common cortical space\n----------------------------------\n\nNormally you would read in estimates across several subjects and morph them\nto the same cortical space (e.g. fsaverage). For example purposes, we will\nsimulate this by just having each \"subject\" have the same response (just\nnoisy in source space) here.\n\nWe'll only consider the left hemisphere in this tutorial.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "n_vertices_sample, n_times = conditions[0].lh_data.shape\nn_subjects = 7\nprint('Simulating data for %d subjects.' % n_subjects)\n\n# Let's make sure our results replicate, so set the seed.\nnp.random.seed(0)\nX = randn(n_vertices_sample, n_times, n_subjects, 4) * 10\nfor ii, condition in enumerate(conditions):\n X[:, :, :, ii] += condition.lh_data[:, :, np.newaxis]" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "It's a good idea to spatially smooth the data, and for visualization\npurposes, let's morph these to fsaverage, which is a grade 5 source space\nwith vertices 0:10242 for each hemisphere. Usually you'd have to morph\neach subject's data separately (and you might want to use morph_data\ninstead), but here since all estimates are on 'sample' we can use one\nmorph matrix for all the heavy lifting.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "fsave_vertices = [np.arange(10242), np.array([], int)] # right hemi is empty\nmorph_mat = compute_morph_matrix('sample', 'fsaverage', sample_vertices,\n fsave_vertices, 20, subjects_dir)\nn_vertices_fsave = morph_mat.shape[0]\n\n# We have to change the shape for the dot() to work properly\nX = X.reshape(n_vertices_sample, n_times * n_subjects * 4)\nprint('Morphing data.')\nX = morph_mat.dot(X) # morph_mat is a sparse matrix\nX = X.reshape(n_vertices_fsave, n_times, n_subjects, 4)" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Now we need to prepare the group matrix for the ANOVA statistic. To make the\nclustering function work correctly with the ANOVA function X needs to be a\nlist of multi-dimensional arrays (one per condition) of shape: samples\n(subjects) x time x space.\n\nFirst we permute dimensions, then split the array into a list of conditions\nand discard the empty dimension resulting from the split using numpy squeeze.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "X = np.transpose(X, [2, 1, 0, 3]) #\nX = [np.squeeze(x) for x in np.split(X, 4, axis=-1)]" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Prepare function for arbitrary contrast\n---------------------------------------\nAs our ANOVA function is a multi-purpose tool we need to apply a few\nmodifications to integrate it with the clustering function. This\nincludes reshaping data, setting default arguments and processing\nthe return values. For this reason we'll write a tiny dummy function.\n\nWe will tell the ANOVA how to interpret the data matrix in terms of\nfactors. This is done via the factor levels argument which is a list\nof the number factor levels for each factor.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "factor_levels = [2, 2]" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Finally we will pick the interaction effect by passing 'A:B'.\n(this notation is borrowed from the R formula language). Without this also\nthe main effects will be returned.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "effects = 'A:B'\n# Tell the ANOVA not to compute p-values which we don't need for clustering\nreturn_pvals = False\n\n# a few more convenient bindings\nn_times = X[0].shape[1]\nn_conditions = 4" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "A stat_fun must deal with a variable number of input arguments.\n\nInside the clustering function each condition will be passed as flattened\narray, necessitated by the clustering procedure. The ANOVA however expects an\ninput array of dimensions: subjects X conditions X observations (optional).\n\nThe following function catches the list input and swaps the first and the\nsecond dimension, and finally calls ANOVA.\n\nNote. for further details on this ANOVA function consider the\ncorresponding\n`time-frequency tutorial `.\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "def stat_fun(*args):\n return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,\n effects=effects, return_pvals=return_pvals)[0]\n # get f-values only." ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Compute clustering statistic\n----------------------------\n\nTo use an algorithm optimized for spatio-temporal clustering, we\njust pass the spatial connectivity matrix (instead of spatio-temporal).\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "source_space = grade_to_tris(5)\n# as we only have one hemisphere we need only need half the connectivity\nlh_source_space = source_space[source_space[:, 0] < 10242]\nprint('Computing connectivity.')\nconnectivity = spatial_tris_connectivity(lh_source_space)\n\n# Now let's actually do the clustering. Please relax, on a small\n# notebook and one single thread only this will take a couple of minutes ...\npthresh = 0.0005\nf_thresh = f_threshold_mway_rm(n_subjects, factor_levels, effects, pthresh)\n\n# To speed things up a bit we will ...\nn_permutations = 128 # ... run fewer permutations (reduces sensitivity)\n\nprint('Clustering.')\nT_obs, clusters, cluster_p_values, H0 = clu = \\\n spatio_temporal_cluster_test(X, connectivity=connectivity, n_jobs=1,\n threshold=f_thresh, stat_fun=stat_fun,\n n_permutations=n_permutations,\n buffer_size=None)\n# Now select the clusters that are sig. at p < 0.05 (note that this value\n# is multiple-comparisons corrected).\ngood_cluster_inds = np.where(cluster_p_values < 0.05)[0]" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Visualize the clusters\n----------------------\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "print('Visualizing clusters.')\n\n# Now let's build a convenient representation of each cluster, where each\n# cluster becomes a \"time point\" in the SourceEstimate\nstc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep,\n vertices=fsave_vertices,\n subject='fsaverage')\n\n# Let's actually plot the first \"time point\" in the SourceEstimate, which\n# shows all the clusters, weighted by duration\n\nsubjects_dir = op.join(data_path, 'subjects')\n# The brighter the color, the stronger the interaction between\n# stimulus modality and stimulus location\n\nbrain = stc_all_cluster_vis.plot(subjects_dir=subjects_dir, colormap='mne',\n views='lateral',\n time_label='Duration significant (ms)')\nbrain.save_image('cluster-lh.png')\nbrain.show_view('medial')" ], "outputs": [], "metadata": { "collapsed": false } }, { "source": [ "Finally, let's investigate interaction effect by reconstructing the time\ncourses\n\n" ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "inds_t, inds_v = [(clusters[cluster_ind]) for ii, cluster_ind in\n enumerate(good_cluster_inds)][0] # first cluster\n\ntimes = np.arange(X[0].shape[1]) * tstep * 1e3\n\nplt.figure()\ncolors = ['y', 'b', 'g', 'purple']\nevent_ids = ['l_aud', 'r_aud', 'l_vis', 'r_vis']\n\nfor ii, (condition, color, eve_id) in enumerate(zip(X, colors, event_ids)):\n # extract time course at cluster vertices\n condition = condition[:, :, inds_v]\n # normally we would normalize values across subjects but\n # here we use data from the same subject so we're good to just\n # create average time series across subjects and vertices.\n mean_tc = condition.mean(axis=2).mean(axis=0)\n std_tc = condition.std(axis=2).std(axis=0)\n plt.plot(times, mean_tc.T, color=color, label=eve_id)\n plt.fill_between(times, mean_tc + std_tc, mean_tc - std_tc, color='gray',\n alpha=0.5, label='')\n\nymin, ymax = mean_tc.min() - 5, mean_tc.max() + 5\nplt.xlabel('Time (ms)')\nplt.ylabel('Activation (F-values)')\nplt.xlim(times[[0, -1]])\nplt.ylim(ymin, ymax)\nplt.fill_betweenx((ymin, ymax), times[inds_t[0]],\n times[inds_t[-1]], color='orange', alpha=0.3)\nplt.legend()\nplt.title('Interaction between stimulus-modality and location.')\nplt.show()" ], "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" } } } }