def run_evoked(subject_id): subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) epochs = mne.read_epochs(op.join(data_path, '%s-epo.fif' % subject), preload=False) evoked_famous = epochs['face/famous'].average() evoked_scrambled = epochs['scrambled'].average() evoked_unfamiliar = epochs['face/unfamiliar'].average() # Simplify comment evoked_famous.comment = 'famous' evoked_scrambled.comment = 'scrambled' evoked_unfamiliar.comment = 'unfamiliar' contrast = mne.combine_evoked([evoked_famous, evoked_unfamiliar, evoked_scrambled], weights=[0.5, 0.5, -1.]) contrast.comment = 'contrast' faces = mne.combine_evoked([evoked_famous, evoked_unfamiliar], 'nave') faces.comment = 'faces' mne.evoked.write_evokeds(op.join(data_path, '%s-ave.fif' % subject), [evoked_famous, evoked_scrambled, evoked_unfamiliar, contrast, faces]) # take care of noise cov cov = mne.compute_covariance(epochs, tmax=0, method='shrunk') cov.save(op.join(data_path, '%s-cov.fif' % subject))
def test_evoked_arithmetic(): """Test evoked arithmetic """ ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = ev1 + ev2 assert_equal(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) ev = ev1 - ev2 assert_equal(ev.nave, ev1.nave + ev2.nave) assert_equal(ev.comment, ev1.comment + ' - ' + ev2.comment) assert_allclose(ev.data, np.ones_like(ev1.data)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ev = merge_evoked([ev1, ev2]) assert_true(len(w) >= 1) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ev = ev1 - ev2 assert_equal(ev.comment, 'unknown') ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_equal(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2)
def test_make_inverse_operator_vector(): """Test MNE inverse computation (vector result).""" fwd_surf = read_forward_solution_meg(fname_fwd, surf_ori=True) fwd_fixed = read_forward_solution_meg(fname_fwd, surf_ori=False) evoked = _get_evoked() noise_cov = read_cov(fname_cov) # Make different version of the inverse operator inv_1 = make_inverse_operator(evoked.info, fwd_fixed, noise_cov, loose=1) inv_2 = make_inverse_operator(evoked.info, fwd_surf, noise_cov, depth=None, use_cps=True) inv_3 = make_inverse_operator(evoked.info, fwd_surf, noise_cov, fixed=True, use_cps=True) inv_4 = make_inverse_operator(evoked.info, fwd_fixed, noise_cov, loose=.2, depth=None) # Apply the inverse operators and check the result for ii, inv in enumerate((inv_1, inv_2, inv_4)): # Don't do eLORETA here as it will be quite slow methods = ['MNE', 'dSPM', 'sLORETA'] if ii < 2 else ['MNE'] for method in methods: stc = apply_inverse(evoked, inv, method=method) stc_vec = apply_inverse(evoked, inv, pick_ori='vector', method=method) assert_allclose(stc.data, stc_vec.magnitude().data) # Vector estimates don't work when using fixed orientations pytest.raises(RuntimeError, apply_inverse, evoked, inv_3, pick_ori='vector') # When computing with vector fields, computing the difference between two # evokeds and then performing the inverse should yield the same result as # computing the difference between the inverses. evoked0 = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked0.crop(0, 0.2) evoked1 = read_evokeds(fname_data, condition=1, baseline=(None, 0)) evoked1.crop(0, 0.2) diff = combine_evoked((evoked0, evoked1), [1, -1]) stc_diff = apply_inverse(diff, inv_1, method='MNE') stc_diff_vec = apply_inverse(diff, inv_1, method='MNE', pick_ori='vector') stc_vec0 = apply_inverse(evoked0, inv_1, method='MNE', pick_ori='vector') stc_vec1 = apply_inverse(evoked1, inv_1, method='MNE', pick_ori='vector') assert_allclose(stc_diff_vec.data, (stc_vec0 - stc_vec1).data, atol=1e-20) assert_allclose(stc_diff.data, (stc_vec0 - stc_vec1).magnitude().data, atol=1e-20)
############################################################################## # Or another one stored in the same file: evoked2 = mne.read_evokeds(evoked_fname, condition='Right Auditory', baseline=(None, 0), proj=True) ############################################################################## # Two evoked objects can be contrasted using :func:`mne.combine_evoked`. # This function can use ``weights='equal'``, which provides a simple # element-by-element subtraction (and sets the # :attr:`mne.Evoked.nave` attribute properly based on the underlying number # of trials) using either equivalent call: contrast = mne.combine_evoked([evoked1, evoked2], weights=[0.5, -0.5]) contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal') print(contrast) ############################################################################## # To do a weighted sum based on the number of averages, which will give # you what you would have gotten from pooling all trials together in # :class:`mne.Epochs` before creating the :class:`mne.Evoked` instance, # you can use ``weights='nave'``: average = mne.combine_evoked([evoked1, evoked2], weights='nave') print(contrast) ############################################################################## # Instead of dealing with mismatches in the number of averages, we can use # trial-count equalization before computing a contrast, which can have some
# button press). You can view the topographies from a certain time span by # painting an area with clicking and holding the left mouse button. evoked_std.plot(window_title='Standard', gfp=True) evoked_dev.plot(window_title='Deviant', gfp=True) ############################################################################### # Show activations as topography figures. times = np.arange(0.05, 0.301, 0.025) evoked_std.plot_topomap(times=times, title='Standard') evoked_dev.plot_topomap(times=times, title='Deviant') ############################################################################### # We can see the MMN effect more clearly by looking at the difference between # the two conditions. P50 and N100 are no longer visible, but MMN/P200 and # P300 are emphasised. evoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal') evoked_difference.plot(window_title='Difference', gfp=True) ############################################################################### # Source estimation. # We compute the noise covariance matrix from the empty room measurement # and use it for the other runs. reject = dict(mag=4e-12) cov = mne.compute_raw_covariance(raw_erm, reject=reject) cov.plot(raw_erm.info) del raw_erm ############################################################################### # The transformation is read from a file. More information about coregistering # the data, see :ref:`ch_interactive_analysis` or # :func:`mne.gui.coregistration`.
event_id = {"left/auditory": 1, "right/auditory": 2, "left/visual": 3, "right/visual": 4} epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax, reject=reject) epochs = mne.Epochs(raw, **epochs_params) print(epochs) ############################################################################### # Next, we create averages of stimulation-left vs stimulation-right trials. # We can use basic arithmetic to, for example, construct and plot # difference ERPs. left, right = epochs["left"].average(), epochs["right"].average() # create and plot difference ERP mne.combine_evoked([left, -right], weights="equal").plot_joint() ############################################################################### # This is an equal-weighting difference. If you have imbalanced trial numbers, # you could also consider either equalizing the number of events per # condition (using # :meth:`epochs.equalize_epochs_counts <mne.Epochs.equalize_event_counts`). # As an example, first, we create individual ERPs for each condition. aud_l = epochs["auditory", "left"].average() aud_r = epochs["auditory", "right"].average() vis_l = epochs["visual", "left"].average() vis_r = epochs["visual", "right"].average() all_evokeds = [aud_l, aud_r, vis_l, vis_r] print(all_evokeds)
stim=True, exclude=bads) # create the real-time epochs object and start acquisition rt_epochs = RtEpochs(rt_client, event_id, tmin, tmax, stim_channel='STI 014', picks=picks, reject=dict(grad=4000e-13, eog=150e-6), decim=1, isi_max=2.0, proj=None) rt_epochs.start() for ii, ev in enumerate(rt_epochs.iter_evoked()): print("Just got epoch %d" % (ii + 1)) ev.pick_types(meg=True, eog=False) if ii == 0: evoked = ev else: evoked = mne.combine_evoked([evoked, ev], weights='nave') ax[0].cla() ax[1].cla() # clear axis plot_events(rt_epochs.events[-5:], sfreq=ev.info['sfreq'], first_samp=-rt_client.tmin_samp, axes=ax[0]) # plot on second subplot evoked.plot(axes=ax[1], selectable=False, time_unit='s') ax[1].set_title('Evoked response for gradiometer channels' '(event_id = %d)' % event_id) plt.pause(0.05 / speedup) plt.draw() rt_epochs.stop()
""" import os.path as op import mne from library.config import meg_dir all_evokeds = [[], [], [], [], []] # Container for all the categories exclude = [1, 5, 16] # Excluded subjects for run in range(1, 20): if run in exclude: continue subject = "sub%03d" % run print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) evokeds = mne.read_evokeds(op.join(meg_dir, subject, '%s-ave.fif' % subject)) for idx, evoked in enumerate(evokeds): all_evokeds[idx].append(evoked) # Insert to the container for idx, evokeds in enumerate(all_evokeds): all_evokeds[idx] = mne.combine_evoked(evokeds, 'equal') # Combine subjects mne.evoked.write_evokeds(op.join(meg_dir, 'grand_average-ave.fif'), all_evokeds)
total = [] for sid in args.subject: # Find the statistics file for this subject path = f"{INPUT_DIR}/{sid}/*-ave.fif" find = glob.glob(path) if len(find) == 0: logging.fatal(f"No summary file found for {sid}") sys.exit(1) elif len(find) > 1: logging.warn(f"Multiple summary files found for {sid}, picking first") total_file = find[0] total += mne.read_evokeds(total_file, baseline=BASELINE) all_average = mne.combine_evoked(total, weights='nave') logging.info(f"Read {args.subject} from {INPUT_DIR}, creating plots in {OUTPUT_DIR}") def plot(electrode, scale=2.5, auto=False): if electrode is None: pick = "all" electrode = "all" else: pick = all_average.ch_names.index(electrode) fig, ax = plt.subplots(figsize=(4, 8/3)) ax.axvline(x=0, color='black') ax.axhline(y=0, color='black')
tfce = dict(start=.2, step=.2) t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test( X, tfce, n_permutations=100) significant_points = cluster_pv.reshape(t_obs.shape).T < .05 print(str(significant_points.sum()) + " points selected by TFCE ...") ############################################################################## # The results of these mass univariate analyses can be visualised by plotting # :class:`mne.Evoked` objects as images (via :class:`mne.Evoked.plot_image`) # and masking points for significance. # Here, we group channels by Regions of Interest to facilitate localising # effects on the head. # We need an evoked object to plot the image to be masked evoked = mne.combine_evoked([long.average(), -short.average()], weights='equal') # calculate difference wave time_unit = dict(time_unit="s") evoked.plot_joint(title="Long vs. short words", ts_args=time_unit, topomap_args=time_unit) # show difference wave # Create ROIs by checking channel labels selections = make_1020_channel_selections(evoked.info, midline="12z") # Visualize the results fig, axes = plt.subplots(nrows=3, figsize=(8, 8)) vmax = np.abs(evoked.data).max() * 1e6 # Iterate over ROIs and axes axes = axes.ravel().tolist() for selection_name, ax in zip(sorted(selections.keys()), axes): picks = selections[selection_name]
mne.write_evokeds(evoked=evoked_vis_r,fname= '%fname_vis_r-ave.fif') # more visualisation evoked_vis_r.plot_topomap(times=np.arange(-0.1, 0.4, 0.05)) ts_args = dict(gfp=True) topomap_args = dict(sensors=False) evoked_vis_r.plot_joint(title='Visual (flashing right) evoked response', times = [.0, 0.075, 0.125, 0.25], ts_args=ts_args, topomap_args=topomap_args) left, right = epochs["vis_l"].average(), epochs["vis_r"].average() # create and plot difference ERP mne.combine_evoked([left, -right], weights='equal').plot_joint(times=np.arange(-0.2,0.5,0.15)) # ### "Letter" inhibition trigger tmin = -0.5 # start of each epoch (200ms before the trigger) tmax = 1 # end of each epoch (1000ms after the trigger) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=baseline, preload=True, reject=reject) epochs.drop_bad() epochs_lett = epochs.pick_channels(['E31','E32','E26','E25','E18','E19','E20','E27' 'E33','E37','E9','E8','E24', 'E43','E52','E53','E80','E90','E81','E132','E157','E148', 'E137','E125','E149','E116','E45','E186','E17']) evoked_lett = epochs_lett['lett'].average() evoked_lett.plot(titles='Button go/nogo evoked response', spatial_colors=True, gfp=True)
# Set up events events = mne.find_events(raw) event_id = {'Aud/L': 1, 'Aud/R': 2} tmin, tmax = -.1, .5 # regular epoching picks = mne.pick_types(raw.info, meg=True) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, reject=None, baseline=None, preload=True, verbose=False) # rERF evokeds = linear_regression_raw(raw, events=events, event_id=event_id, reject=None, tmin=tmin, tmax=tmax) # linear_regression_raw returns a dict of evokeds # select conditions similarly to mne.Epochs objects # plot both results, and their difference cond = "Aud/L" fig, (ax1, ax2, ax3) = plt.subplots(3, 1) params = dict(spatial_colors=True, show=False, ylim=dict(grad=(-200, 200)), time_unit='s') epochs[cond].average().plot(axes=ax1, **params) evokeds[cond].plot(axes=ax2, **params) contrast = mne.combine_evoked([evokeds[cond], -epochs[cond].average()], weights='equal') contrast.plot(axes=ax3, **params) ax1.set_title("Traditional averaging") ax2.set_title("rERF") ax3.set_title("Difference") plt.show()
t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test( X, tfce, adjacency=adjacency, n_permutations=100) # a more standard number would be 1000+ significant_points = cluster_pv.reshape(t_obs.shape).T < .05 print(str(significant_points.sum()) + " points selected by TFCE ...") ############################################################################## # The results of these mass univariate analyses can be visualised by plotting # :class:`mne.Evoked` objects as images (via :class:`mne.Evoked.plot_image`) # and masking points for significance. # Here, we group channels by Regions of Interest to facilitate localising # effects on the head. # We need an evoked object to plot the image to be masked evoked = mne.combine_evoked( [long_words.average(), short_words.average()], weights=[1, -1]) # calculate difference wave time_unit = dict(time_unit="s") evoked.plot_joint(title="Long vs. short words", ts_args=time_unit, topomap_args=time_unit) # show difference wave # Create ROIs by checking channel labels selections = make_1020_channel_selections(evoked.info, midline="12z") # Visualize the results fig, axes = plt.subplots(nrows=3, figsize=(8, 8)) axes = {sel: ax for sel, ax in zip(selections, axes.ravel())} evoked.plot_image(axes=axes, group_by=selections, colorbar=False,
############################################################################################## #### By Condition #### ############################################################################################## ####################################### Tactile/Tactile ###################################### evoked_left_cued_TT = get_topo( raw, {'LT/LT': 25}, np.arange(.060, .120, .010), 0.005, tmin, tmax, reject_num = 100e-6 ) evoked_right_cued_TT = get_topo(raw, {'RT/RT': 35}, np.arange(.060, .120, .010), 0.005, tmin, tmax, reject_num=100e-6) evoked_left_uncued_TT = get_topo( raw, {'RT/LT': 33}, np.arange(.060, .120, .010), 0.005, tmin, tmax, reject_num = 100e-6 ) evoked_right_uncued_TT = get_topo( raw, {'LT/RT': 27}, np.arange(.060, .120, .010), 0.005, tmin, tmax, reject_num = 100e-6 ) # get individual effect plots ind_left_red_TT = mne.combine_evoked([evoked_left_cued_TT, evoked_left_uncued_TT], weights=[1, -1]) # subtraction ind_left_red_TT.plot_topomap([.090], ch_type='eeg', show_names=True, average=0.030) fig = plt.gcf() fig.set_size_inches(18.5, 10.5) plt.savefig('%s/P_topo/%s_left_red_TT_topomap.png' % (directory, participant)) if dont_plot: plt.close() # get individual effect plots ind_right_red_TT = mne.combine_evoked([evoked_right_cued_TT, evoked_right_uncued_TT], weights=[1, -1]) # subtraction ind_right_red_TT.plot_topomap([.090], ch_type='eeg', show_names=True, average=0.030) fig = plt.gcf() fig.set_size_inches(18.5, 10.5) plt.savefig('%s/P_topo/%s_right_red_TT_topomap.png' % (directory, participant)) if dont_plot:
reward.data = data no_reward = epochs[no_reward_left_maze+no_reward_right_maze].average() no_reward.apply_baseline(baseline=(-0.2,0)) data_norew = no_reward.data FCz= np.array([data_norew[22], data_norew[14], data_norew[5], data_norew[6], data_norew[7], data_norew[8], data_norew[14]]).mean(axis=0) P8= np.array([data_norew[170], data_norew[177], data_norew[178], data_norew[169], data_norew[168], data_norew[160], data_norew[159]]).mean(axis=0) data_norew[14] = FCz data_norew[169] = P8 no_reward.data = data_norew # Compute difference wave difference_wave = mne.combine_evoked((reward,no_reward),[-1,1]) # Plot new channels and difference wave colors = dict(Reward_maze = "darkblue", No_reward_maze = "darkred", Difference_Wave = 'black') evoked_dict = {'Reward_maze': evoked1, 'No_reward_maze': evoked2, 'Difference_Wave': difference_wave} linestyles = dict(Reward_maze = '-', No_reward_maze = '--', Difference_Wave = '-') ch_name='' picks=evoked1.ch_names.index(ch_name) fig=mne.viz.plot_compare_evokeds(evoked_dict, picks=picks, truncate_yaxis=False, truncate_xaxis=False, colors=colors, linestyles=linestyles, invert_y=True, ylim = dict(eeg=[-8,8]),
tmin=tmin, tmax=tmax, reject=reject) epochs = mne.Epochs(raw, **epochs_params) print(epochs) ############################################################################### # Next, we create averages of stimulation-left vs stimulation-right trials. # We can use basic arithmetic to, for example, construct and plot # difference ERPs. left, right = epochs["left"].average(), epochs["right"].average() # create and plot difference ERP mne.combine_evoked([left, -right], weights='equal').plot_joint() ############################################################################### # This is an equal-weighting difference. If you have imbalanced trial numbers, # you could also consider either equalizing the number of events per # condition (using # :meth:`epochs.equalize_event_counts <mne.Epochs.equalize_event_counts>`). # As an example, first, we create individual ERPs for each condition. aud_l = epochs["auditory", "left"].average() aud_r = epochs["auditory", "right"].average() vis_l = epochs["visual", "left"].average() vis_r = epochs["visual", "right"].average() all_evokeds = [aud_l, aud_r, vis_l, vis_r] print(all_evokeds)
evoked_hcp = None hcp_evokeds = hcp.read_evokeds(onset='stim', **hcp_params) for ev in hcp_evokeds: if not ev.comment == 'Wrkmem_LM-TIM-face_BT-diff_MODE-mag': continue # Once more we add and interpolate missing channels evoked_hcp = preproc.interpolate_missing(ev, **hcp_params) ############################################################################## # Time to compare the outputs # evoked = mne.combine_evoked(evokeds, weights='equal') evoked_from_epochs_hcp = mne.combine_evoked( evokeds_from_epochs_hcp, weights='equal') fig1, axes = plt.subplots(3, 1, figsize=(12, 8)) evoked.plot(axes=axes[0], show=False) axes[0].set_title('MNE-HCP') evoked_from_epochs_hcp.plot(axes=axes[1], show=False) axes[1].set_title('HCP epochs') evoked_hcp.plot(axes=axes[2], show=False) axes[2].set_title('HCP evoked') fig1.canvas.draw()
contrasts = list() for subject_id in range(1, 20): if subject_id in exclude: continue subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) contrast = mne.read_evokeds(op.join(data_path, '%s-ave.fif' % subject), condition='contrast') contrast.pick_types(meg=False, eeg=True) contrast.apply_baseline((-0.2, 0.0)) contrasts.append(contrast) contrast = mne.combine_evoked(contrasts, 'equal') channel = 'EEG070' idx = contrast.ch_names.index(channel) mne.viz.plot_compare_evokeds(contrast, [idx]) ############################################################################## # Assemble the data and run the cluster stats on channel data data = np.array([c.data[idx] for c in contrasts]) n_permutations = 1000 # number of permutations to run # set family-wise p-value p_accept = 0.01
psd_evo2.comment = "Second" # Any Evoked can be plotted e.g. as a topo. # as far as MNE knows, this is an ERP, so the X and Y axis # will not be correctly titled, i.e. the X axis will say it's # time, when it's actually frequency. Just ignore for now. The # values themselves are correct. psd_evo1.plot_topo() # plot multiple plot_evoked_topo([psd_evo1, psd_evo2]) # subtract condition two from one # note this function is very general, and can perform any # linear operation on any set of Evokeds one_minus_two = combine_evoked([psd_evo1, psd_evo2], [1, -1]) one_minus_two.comment = "one - two" one_minus_two.plot_topo() # Note that the channels names have the generic, Neuromag names, i.e. # "MEGXXX." The automatic channel layout identifier gets # confused by the native "AXXX" Magnes3600 names, and so functions such as # plot_topo fail, because they cannot figure out the physical locations # of the channels. One way to solve this problem is to convert the channel # names to Neuromag names with psd_to_evo(keep_ch_names=False). This is # the approach used above. Alternatively, if you want to keep the Magnes # names, then you need to specify the layout manually, like so: psd_evo1 = psd_to_evo(psd1, freqs1, epo1) psd_evo1.comment = "First" layout = fix_layout(psd_evo1)
tfce = dict(start=.2, step=.2) t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test( X, tfce, n_permutations=100) # a more standard number would be 1000+ significant_points = cluster_pv.reshape(t_obs.shape).T < .05 print(str(significant_points.sum()) + " points selected by TFCE ...") ############################################################################## # The results of these mass univariate analyses can be visualised by plotting # :class:`mne.Evoked` objects as images (via :class:`mne.Evoked.plot_image`) # and masking points for significance. # Here, we group channels by Regions of Interest to facilitate localising # effects on the head. # We need an evoked object to plot the image to be masked evoked = mne.combine_evoked([long_words.average(), -short_words.average()], weights='equal') # calculate difference wave time_unit = dict(time_unit="s") evoked.plot_joint(title="Long vs. short words", ts_args=time_unit, topomap_args=time_unit) # show difference wave # Create ROIs by checking channel labels selections = make_1020_channel_selections(evoked.info, midline="12z") # Visualize the results fig, axes = plt.subplots(nrows=3, figsize=(8, 8)) axes = {sel: ax for sel, ax in zip(selections, axes.ravel())} evoked.plot_image(axes=axes, group_by=selections, colorbar=False, show=False, mask=significant_points, show_names="all", titles=None, **time_unit) plt.colorbar(axes["Left"].images[-1], ax=list(axes.values()), shrink=.3, label="uV")
# average epochs and get Evoked datasets #evokeds = [epochs[cond].average() for cond in ['stim/face', 'stim/house', 'imag/face', 'imag/house' ]] #all_evokeds = dict((cond, epochs[cond].average()) for cond in event_id) #print(all_evokeds['stim/face']) #channel_ind = mne.pick_channels(epochs.info['ch_names'], ['PO8']) stim_face, stim_house = epochs['stim/face'].average(), epochs['stim/house'].average() imag_face, imag_house = epochs['imag/face'].average(), epochs['imag/house'].average() # plot perception menus imagery diff_evoked = mne.combine_evoked([stim_face, -stim_house ], weights= 'equal') diff_evoked.plot(spatial_colors=True, axes=ax[coord[count]], titles = '%s ' %subject) count=count+1 diff_evoked.plot_joint(title = '%s ERP diff Perception Face-House' %subject))
# Fit ICA, find and remove major artifacts ica = ICA(n_components=0.95, random_state=0).fit(raw, decim=1, reject=reject) # compute correlation scores, get bad indices sorted by score eog_epochs = create_eog_epochs(raw, ch_name='MRT31-2908', reject=reject) eog_inds, eog_scores = ica.find_bads_eog(eog_epochs, ch_name='MRT31-2908') ica.plot_scores(eog_scores, eog_inds) # see scores the selection is based on ica.plot_components(eog_inds) # view topographic sensitivity of components ica.exclude += eog_inds[:1] # we saw the 2nd ECG component looked too dipolar ica.plot_overlay(eog_epochs.average()) # inspect artifact removal ica.apply(epochs) # clean data, default in place evoked = [epochs[k].average() for k in event_ids] contrast = combine_evoked(evoked, weights=[-1, 1]) # Faces - scrambled evoked.append(contrast) for e in evoked: e.plot(ylim=dict(mag=[-400, 400])) plt.show() # estimate noise covarariance noise_cov = mne.compute_covariance(epochs, tmax=0, method='shrunk', rank=None) ############################################################################### # Visualize fields on MEG helmet
raw.filter(.5,35,filter_length='auto', l_trans_bandwidth='auto',h_trans_bandwidth='auto') events = pyi.utils.run_events(raw)[0] picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True, stim=False) event_id = dict(angry_faces=1, fearful_faces=2, houses=3, neutral_faces=4, flipped_neutral_faces=5) tmin, tmax, baseline = -.25, 1,(-.25, 0) reject=dict(grad=4000e-13, eog=350e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=baseline, reject=reject, preload=True, add_eeg_ref=False) epochs.resample(150., npad='auto') epochs.equalize_event_counts(epochs.event_id) evokeds = {key:epochs[key].average() for key in event_id.keys()} contrast = mne.combine_evoked([evokeds['neutral_faces'], - evokeds['houses']], weights='equal') contrast.plot_joint([.1,.2,.3,.4]) picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False) reject = dict(grad=4000e-13, mag=4e-12) #cov = mne.compute_raw_covariance(raw_erm,reject=reject,picks=picks) cov =pyi.utils.compute_cov(epochs,reject=reject) fwd, inv = pyi.utils.run_fwd_inv(raw_fname, subject, cov=cov, fname_trans=trans,subjects_dir = subjects_dir) snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" pick_ori = None
# painting an area with clicking and holding the left mouse button. evoked_std.plot(window_title='Standard', gfp=True, time_unit='s') evoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s') ############################################################################### # Show activations as topography figures. times = np.arange(0.05, 0.301, 0.025) evoked_std.plot_topomap(times=times, title='Standard', time_unit='s') evoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s') ############################################################################### # We can see the MMN effect more clearly by looking at the difference between # the two conditions. P50 and N100 are no longer visible, but MMN/P200 and # P300 are emphasised. evoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal') evoked_difference.plot(window_title='Difference', gfp=True, time_unit='s') ############################################################################### # Source estimation. # We compute the noise covariance matrix from the empty room measurement # and use it for the other runs. reject = dict(mag=4e-12) cov = mne.compute_raw_covariance(raw_erm, reject=reject) cov.plot(raw_erm.info) del raw_erm ############################################################################### # The transformation is read from a file. More information about coregistering # the data, see :ref:`ch_interactive_analysis` or # :func:`mne.gui.coregistration`.
def test_arithmetic(): """Test evoked arithmetic.""" ev = read_evokeds(fname, condition=0) ev20 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev30 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=30) tol = dict(rtol=1e-9, atol=0) # test subtraction sub1 = combine_evoked([ev, ev], weights=[1, -1]) sub2 = combine_evoked([ev, -ev], weights=[1, 1]) assert np.allclose(sub1.data, np.zeros_like(sub1.data), atol=1e-20) assert np.allclose(sub2.data, np.zeros_like(sub2.data), atol=1e-20) # test nave weighting. Expect signal ampl.: 1*(20/50) + 1*(30/50) == 1 # and expect nave == ev1.nave + ev2.nave ev = combine_evoked([ev20, ev30], weights='nave') assert np.allclose(ev.nave, ev20.nave + ev30.nave) assert np.allclose(ev.data, np.ones_like(ev.data), **tol) # test equal-weighted sum. Expect signal ampl. == 2 # and expect nave == 1/sum(1/naves) == 1/(1/20 + 1/30) == 12 ev = combine_evoked([ev20, ev30], weights=[1, 1]) assert np.allclose(ev.nave, 12.) assert np.allclose(ev.data, ev20.data + ev30.data, **tol) # test equal-weighted average. Expect signal ampl. == 1 # and expect nave == 1/sum(weights²/naves) == 1/(0.5²/20 + 0.5²/30) == 48 ev = combine_evoked([ev20, ev30], weights='equal') assert np.allclose(ev.nave, 48.) assert np.allclose(ev.data, np.mean([ev20.data, ev30.data], axis=0), **tol) # test zero weights ev = combine_evoked([ev20, ev30], weights=[1, 0]) assert ev.nave == ev20.nave assert np.allclose(ev.data, ev20.data, **tol) # default comment behavior if evoked.comment is None old_comment1 = ev20.comment ev20.comment = None ev = combine_evoked([ev20, -ev30], weights=[1, -1]) assert_equal(ev.comment.count('unknown'), 2) assert ev.comment == 'unknown + unknown' ev20.comment = old_comment1 with pytest.raises(ValueError, match="Invalid value for the 'weights'"): combine_evoked([ev20, ev30], weights='foo') with pytest.raises(ValueError, match='weights must be the same size as'): combine_evoked([ev20, ev30], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2) with pytest.raises(TypeError, match='All elements must be an instance of'): grand_average([1, evoked1]) gave = grand_average([ev20, ev20, -ev30]) # (1 + 1 + -1) / 3 = 1/3 assert_allclose(gave.data, np.full_like(gave.data, 1. / 3.)) # test channel (re)ordering evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) data2 = evoked2.data # assumes everything is ordered to the first evoked data = (evoked1.data + evoked2.data) / 2. evoked2.reorder_channels(evoked2.ch_names[::-1]) assert not np.allclose(data2, evoked2.data) with pytest.warns(RuntimeWarning, match='reordering'): evoked3 = combine_evoked([evoked1, evoked2], weights=[0.5, 0.5]) assert np.allclose(evoked3.data, data) assert evoked1.ch_names != evoked2.ch_names assert evoked1.ch_names == evoked3.ch_names
# clean up del linear_model ############################################################################### # compute mean beta-coefficient for predictor phase-coherence # subject ids subjects = [str(subj) for subj in subjects] # extract phase-coherence betas for each subject phase_coherence = [betas_evoked[subj]['phase-coherence'] for subj in subjects] # average phase-coherence betas weights = np.repeat(1 / len(phase_coherence), len(phase_coherence)) ga_phase_coherence = combine_evoked(phase_coherence, weights=weights) ############################################################################### # compute bootstrap confidence interval for phase-coherence betas and t-values # set random state for replication random_state = 42 random = np.random.RandomState(random_state) # number of random samples boot = 2000 # place holders for bootstrap samples cluster_H0 = np.zeros(boot) f_H0 = np.zeros(boot)
best_idx # rememeber to create a subplot for the colorbar fig, axes = plt.subplots(nrows=1, ncols=4, figsize=[10., 3.4]) vmin, vmax = -400, 400 # make sure each plot has same colour range # first plot the topography at the time of the best fitting (single) dipole plot_params = dict(times=best_time, ch_type='mag', outlines='skirt', colorbar=False) evoked.plot_topomap(time_format='Measured field', axes=axes[0], **plot_params) # compare this to the predicted field pred_evokedd.plot_topomap(time_format='Predicted field', axes=axes[1], **plot_params) # Subtract predicted from measured data (apply equal weights) diff = combine_evoked([evoked, -pred_evokedd], weights='equal') plot_params['colorbar'] = True diff.plot_topomap(time_format='Difference', axes=axes[2], **plot_params) plt.suptitle('Comparison of measured and predicted fields ' 'at {:.0f} ms'.format(best_time * 1000.), fontsize=16) dip_fixed = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0] dip_fixed = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans, pos=dip.pos[best_idx], ori=dip.ori[best_idx])[0] dip_fixed.plot()
def run_evoked(subject_id): subject = "sub%03d" % subject_id print("processing subject: %s" % subject) in_path = op.join(data_path, "EEG_Process") evo_path = op.join(data_path, "EEG_Evoked") for run in range(1, 2): fname = op.join(in_path, 'sub_%03d_raw-epo.fif' % (subject_id, )) epochs = mne.read_epochs(fname, preload=True) #compute covariance for later on (inverse solution) fname_cov = op.join(evo_path, "sub_%03d_LSF_HSF-cov.fif" % (subject_id, )) cv = KFold(3, random_state=97) # make sure cv is deterministic cov = mne.compute_covariance(epochs, tmax=-0.01, method='shrunk', cv=cv) cov.save(fname_cov) mne.viz.plot_cov(cov, epochs.info) #general: HSF vs LSF evoked_LSF = epochs['LSF'].average() evoked_HSF = epochs['HSF'].average() contrast = mne.combine_evoked([evoked_HSF, evoked_LSF], weights=[1, -1]) #name the conditions # Simplify comment evoked_LSF.comment = 'evoked_LSF' evoked_HSF.comment = 'evoked_HSF' contrast.comment = 'contrast' #contrast.plot(picks=('Oz'), window_title='CONTRAST') #plot #evoked_LSF.plot(picks=['Oz'], window_title='evoked, condition LSF, electrode Oz') #evoked_HSF.plot(picks=['Oz'], window_title='evoked, condition HSF, electrode Oz') fname_evo = op.join(evo_path, "sub_%03d_LSF_HSF-ave.fif" % (subject_id, )) mne.evoked.write_evokeds(fname_evo, [evoked_LSF, evoked_HSF, contrast]) #compute forward solution for later on (inverse solution) fname_fwd = op.join(evo_path, "sub_%03d_LSF_HSF-fwd.fif" % (subject_id, )) info = mne.io.read_info(fname_evo) fwd = mne.make_forward_solution(info=info, trans=trans, src=src, bem=bem, eeg=True, mindist=5.0, n_jobs=1) print(fwd) leadfield = fwd['sol']['data'] print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape) mne.write_forward_solution(fname_fwd, fwd, overwrite=True) # for illustration purposes use fwd to compute the sensitivity map eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed') eeg_map.plot(time_label='EEG sensitivity LSF', clim=dict(lims=[5, 50, 100]))
evoked_condition_1 = epochs_condition_1.average() evoked_condition_2 = epochs_condition_2.average() plt.figure() plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43) plt.subplot(2, 1, 1) # Create new stats image with only significant clusters T_obs_plot = np.nan * np.ones_like(T_obs) for c, p_val in zip(clusters, cluster_p_values): if p_val <= 0.05: T_obs_plot[c] = T_obs[c] plt.imshow(T_obs, extent=[times[0], times[-1], freqs[0], freqs[-1]], aspect='auto', origin='lower', cmap='gray') plt.imshow(T_obs_plot, extent=[times[0], times[-1], freqs[0], freqs[-1]], aspect='auto', origin='lower', cmap='RdBu_r') plt.xlabel('Time (ms)') plt.ylabel('Frequency (Hz)') plt.title('Induced power (%s)' % ch_name) ax2 = plt.subplot(2, 1, 2) evoked_contrast = mne.combine_evoked([evoked_condition_1, evoked_condition_2], weights=[1, -1]) evoked_contrast.plot(axes=ax2, time_unit='s') plt.show()
limo_epochs['Face/A'].average().plot_joint(times=[0.15], title='Evoked response: Face A', ts_args=ts_args) # and face B limo_epochs['Face/B'].average().plot_joint(times=[0.15], title='Evoked response: Face B', ts_args=ts_args) ############################################################################### # We can also compute the difference wave contrasting Face A and Face B. # Although, looking at the evoked responses above, we shouldn't expect great # differences among these face-stimuli. # Face A minus Face B difference_wave = combine_evoked( [limo_epochs['Face/A'].average(), limo_epochs['Face/B'].average()], weights=[1, -1]) # plot difference wave difference_wave.plot_joint(times=[0.15], title='Difference Face A - Face B') ############################################################################### # As expected, no clear pattern appears when contrasting # Face A and Face B. However, we could narrow our search a little bit more. # Since this is a "visual paradigm" it might be best to look at electrodes # located over the occipital lobe, as differences between stimuli (if any) # might easier to spot over visual areas. # Create a dictionary containing the evoked responses conditions = ["Face/A", "Face/B"] evokeds = {
pos_psd = np.mean(pos_psds, axis=0) pos.pick_types(meg=True) posev = pos.average() pos_fev = mne.EvokedArray(pos_psd, posev.info, comment="pos") pos_fev.times = pos_freqs neg_psd = np.mean(neg_psds, axis=0) neg.pick_types(meg=True) negev = neg.average() neg_fev = mne.EvokedArray(neg_psd, negev.info, comment="neg") neg_fev.times = neg_freqs # plot & compare the PSDs per condition over channel layout # colors = "black","grey","green","red" # mne.viz.plot_evoked_topo([rest_fev,ton_fev,pos_fev,neg_fev],layout=layout,color=colors) # create evoked condition comparisons ton_minus_rest = mne.combine_evoked([ton_fev, rest_fev], [1, -1]) pos_minus_ton = mne.combine_evoked([pos_fev, ton_fev], [1, -1]) neg_minus_ton = mne.combine_evoked([neg_fev, ton_fev], [1, -1]) neg_minus_pos = mne.combine_evoked([neg_fev, pos_fev], [1, -1]) # plot differences from pos/neg to tone baseline, and tone vs. resting state ton_minus_rest.plot(window_title="ToneBaseline - RestingState", spatial_colors=True) ton_minus_rest.plot_topomap(times=11, average=6.0, title="ToneBaseline - RestingState", cmap='RdBu_r') pos_minus_ton.plot(window_title="Positive - ToneBaseline", spatial_colors=True) pos_minus_ton.plot_topomap(times=11, average=6.0,
evoked_power_1 = epochs_power_1.mean(axis=0) evoked_power_2 = epochs_power_2.mean(axis=0) evoked_power_contrast = evoked_power_1 - evoked_power_2 signs = np.sign(evoked_power_contrast) # Create new stats image with only significant clusters F_obs_plot = np.nan * np.ones_like(F_obs) for c, p_val in zip(clusters, cluster_p_values): if p_val <= 0.05: F_obs_plot[c] = F_obs[c] * signs[c] ax.imshow(F_obs, extent=[times[0], times[-1], freqs[0], freqs[-1]], aspect='auto', origin='lower', cmap='gray') max_F = np.nanmax(abs(F_obs_plot)) ax.imshow(F_obs_plot, extent=[times[0], times[-1], freqs[0], freqs[-1]], aspect='auto', origin='lower', cmap='RdBu_r', vmin=-max_F, vmax=max_F) ax.set_xlabel('Time (ms)') ax.set_ylabel('Frequency (Hz)') ax.set_title(f'Induced power ({ch_name})') # plot evoked evoked_condition_1 = epochs_condition_1.average() evoked_condition_2 = epochs_condition_2.average() evoked_contrast = mne.combine_evoked([evoked_condition_1, evoked_condition_2], weights=[1, -1]) evoked_contrast.plot(axes=ax2, time_unit='s')
contrasts = list() for subject_id in range(1, 20): if subject_id in exclude_subjects: continue subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) contrast = mne.read_evokeds(op.join( data_path, '%s_highpass-%sHz-ave.fif' % (subject, l_freq)), condition='contrast') contrast.pick_types(meg=False, eeg=True).crop(None, 0.8) contrast.apply_baseline((-0.2, 0.0)) contrasts.append(contrast) contrast = mne.combine_evoked(contrasts, 'equal') ############################################################################## # Assemble the data and run the cluster stats on channel data data = np.array([c.data for c in contrasts]) connectivity = None tail = 0. # for two sided test # set cluster threshold p_thresh = 0.01 / (1 + (tail == 0)) n_samples = len(data) threshold = -stats.t.ppf(p_thresh, n_samples - 1) if np.sign(tail) < 0: threshold = -threshold
def test_arithmetic(): """Test evoked arithmetic.""" ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = combine_evoked([ev1, ev2], weights='nave') assert_equal(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # with same trial counts, a bunch of things should be equivalent for weights in ('nave', 'equal', [0.5, 0.5]): ev = combine_evoked([ev1, ev1], weights=weights) assert_allclose(ev.data, ev1.data) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights=weights) assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights='equal') assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev2], weights='equal') expected = int(round(1. / (0.25 / ev1.nave + 0.25 / ev2.nave))) assert_equal(expected, 27) # this is reasonable assert_equal(ev.nave, expected) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None ev = combine_evoked([ev1, -ev2], weights=[1, -1]) assert_equal(ev.comment.count('unknown'), 2) assert ('-unknown' in ev.comment) assert (' + ' in ev.comment) ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_equal(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2) pytest.raises(TypeError, grand_average, [1, evoked1])
def test_arithmetic(): """Test evoked arithmetic.""" ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = combine_evoked([ev1, ev2], weights='nave') assert_allclose(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # with same trial counts, a bunch of things should be equivalent for weights in ('nave', [0.5, 0.5]): ev = combine_evoked([ev1, ev1], weights=weights) assert_allclose(ev.data, ev1.data) assert_allclose(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights=weights) assert_allclose(ev.data, 0., atol=1e-20) assert_allclose(ev.nave, 2 * ev1.nave) # adding evoked to itself ev = combine_evoked([ev1, ev1], weights='equal') assert_allclose(ev.data, 2 * ev1.data) assert_allclose(ev.nave, ev1.nave / 2) # subtracting evoked from itself ev = combine_evoked([ev1, -ev1], weights='equal') assert_allclose(ev.data, 0., atol=1e-20) assert_allclose(ev.nave, ev1.nave / 2) # subtracting different evokeds ev = combine_evoked([ev1, -ev2], weights='equal') assert_allclose(ev.data, 2., atol=1e-20) expected_nave = 1. / (1. / ev1.nave + 1. / ev2.nave) assert_allclose(ev.nave, expected_nave) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None ev = combine_evoked([ev1, -ev2], weights=[1, -1]) assert_equal(ev.comment.count('unknown'), 2) assert ('-unknown' in ev.comment) assert (' + ' in ev.comment) ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_allclose(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2) pytest.raises(TypeError, grand_average, [1, evoked1]) gave = grand_average([ev1, ev1, ev2]) assert_allclose(gave.data, np.ones_like(gave.data)) # test channel (re)ordering evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) data2 = evoked2.data # assumes everything is ordered to the first evoked data = (evoked1.data + evoked2.data) evoked2.reorder_channels(evoked2.ch_names[::-1]) assert not np.allclose(data2, evoked2.data) with pytest.warns(RuntimeWarning, match='reordering'): ev3 = grand_average((evoked1, evoked2)) assert np.allclose(ev3.data, data) assert evoked1.ch_names != evoked2.ch_names assert evoked1.ch_names == ev3.ch_names
# condition (using ``Epochs.equalize_event_counts``), or the ``combine_evoked`` # function. # As an example, first, we create individual ERPs for each condition. aud_l = epochs["auditory", "left"].average() aud_r = epochs["auditory", "right"].average() vis_l = epochs["visual", "left"].average() vis_r = epochs["visual", "right"].average() all_evokeds = [aud_l, aud_r, vis_l, vis_r] # This could have been much simplified with a list comprehension: # all_evokeds = [epochs[cond] for cond in event_id] # Then, we construct and plot an unweighted average of left vs. right trials. mne.combine_evoked(all_evokeds, weights=(1, -1, 1, -1)).plot_joint() ############################################################################### # Often, it makes sense to store Evoked objects in a dictionary or a list - # either different conditions, or different subjects. # If they are stored in a list, they can be easily averaged, for example, # for a grand average across subjects (or conditions). grand_average = mne.grand_average(all_evokeds) mne.write_evokeds('/tmp/tmp-ave.fif', all_evokeds) # If Evokeds objects are stored in a dictionary, they can be retrieved by name. all_evokeds = dict((cond, epochs[cond].average()) for cond in event_id) print(all_evokeds['left/auditory']) # Besides for explicit access, this can be used for example to set titles.
# plotting methods such as `~mne.Evoked.plot_joint` or # `~mne.Evoked.plot_topomap`. Here we'll examine just the EEG channels, and see # the classic auditory evoked N100-P200 pattern over dorso-frontal electrodes, # then plot scalp topographies at some additional arbitrary times: # sphinx_gallery_thumbnail_number = 13 aud_evoked.plot_joint(picks='eeg') aud_evoked.plot_topomap(times=[0., 0.08, 0.1, 0.12, 0.2], ch_type='eeg') ############################################################################## # Evoked objects can also be combined to show contrasts between conditions, # using the `mne.combine_evoked` function. A simple difference can be # generated by passing ``weights=[1, -1]``. We'll then plot the difference wave # at each sensor using `~mne.Evoked.plot_topo`: evoked_diff = mne.combine_evoked([aud_evoked, vis_evoked], weights=[1, -1]) evoked_diff.pick_types(meg='mag').plot_topo(color='r', legend=False) ############################################################################## # Inverse modeling # ^^^^^^^^^^^^^^^^ # # Finally, we can estimate the origins of the evoked activity by projecting the # sensor data into this subject's :term:`source space` (a set of points either # on the cortical surface or within the cortical volume of that subject, as # estimated by structural MRI scans). MNE-Python supports lots of ways of doing # this (dynamic statistical parametric mapping, dipole fitting, beamformers, # etc.); here we'll use minimum-norm estimation (MNE) to generate a continuous # map of activation constrained to the cortical surface. MNE uses a linear # :term:`inverse operator` to project EEG+MEG sensor measurements into the # source space. The inverse operator is computed from the
def test_arithmetic(): """Test evoked arithmetic.""" ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = combine_evoked([ev1, ev2], weights='nave') assert_equal(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # with same trial counts, a bunch of things should be equivalent for weights in ('nave', 'equal', [0.5, 0.5]): ev = combine_evoked([ev1, ev1], weights=weights) assert_allclose(ev.data, ev1.data) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights=weights) assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights='equal') assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev2], weights='equal') expected = int(round(1. / (0.25 / ev1.nave + 0.25 / ev2.nave))) assert_equal(expected, 27) # this is reasonable assert_equal(ev.nave, expected) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None ev = combine_evoked([ev1, -ev2], weights=[1, -1]) assert_equal(ev.comment.count('unknown'), 2) assert_true('-unknown' in ev.comment) assert_true(' + ' in ev.comment) ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_equal(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2) assert_raises(ValueError, grand_average, [1, evoked1])
# button press). You can view the topographies from a certain time span by # painting an area with clicking and holding the left mouse button. evoked_std.plot(window_title='Standard', gfp=True, time_unit='s') evoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s') ############################################################################### # Show activations as topography figures. times = np.arange(0.05, 0.301, 0.025) evoked_std.plot_topomap(times=times, title='Standard', time_unit='s') evoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s') ############################################################################### # We can see the MMN effect more clearly by looking at the difference between # the two conditions. P50 and N100 are no longer visible, but MMN/P200 and # P300 are emphasised. evoked_difference = combine_evoked([evoked_dev, evoked_std], weights=[1, -1]) evoked_difference.plot(window_title='Difference', gfp=True, time_unit='s') ############################################################################### # Source estimation. # We compute the noise covariance matrix from the empty room measurement # and use it for the other runs. reject = dict(mag=4e-12) cov = mne.compute_raw_covariance(raw_erm, reject=reject) cov.plot(raw_erm.info) del raw_erm ############################################################################### # The transformation is read from a file: trans_fname = op.join(data_path, 'MEG', 'bst_auditory', 'bst_auditory-trans.fif')
def plot_artefact_overview(raw_orig, raw_clean, stim_event_ids=[1], stim_ch='STI 014', resp_ch=None, resp_event_ids=None, ecg_ch='EEG 002', eog1_ch='EEG 001', eog2_ch='EEG 003', eog_tmin=-0.5, eog_tmax=0.5, eog_id=998, eog_lfreq=8., eog_hfreq=20., ecg_tmin=-0.5, ecg_tmax=0.5, ecg_id=999, ecg_lfreq=8., ecg_hfreq=20., stim_tmin=-0.2, stim_tmax=0.8, resp_tmin=-0.6, resp_tmax=0.4, eve_output='onset', overview_fname=None): ''' Plot an overview of the artefact rejection with ECG, EOG vertical and EOG horizontal channels. Shows the data before and after cleaning along with a difference plot. raw_orig: instance of mne.io.Raw | str File name of raw object of the uncleaned data. raw_clean: instance of mne.io.Raw | str File name of raw object of the cleaned data. stim_event_ids: list List of stim or resp event ids. Defaults to [1]. resp_event_ids: list List of stim or resp event ids. Defaults to None. eve_output: 'onset' | 'offset' | 'step' Whether to report when events start, when events end, or both. overview_fname: str | None Name to save the plot generated. (considers raw_clean.info['filename']) Notes: Time is always shown in milliseconds (1e3) and the MEG data from mag is always in femtoTesla (fT) (1e15) ''' from mne.preprocessing import create_ecg_epochs, create_eog_epochs raw = check_read_raw(raw_orig, preload=True) raw_clean = check_read_raw(raw_clean, preload=True) if not overview_fname: try: overview_fname = raw_clean.info['filename'].rsplit('-raw.fif')[0] + ',overview-plot.png' except: overview_fname = 'overview-plot.png' # stim related events events = mne.find_events(raw, stim_channel=stim_ch, output='onset') events_clean = mne.find_events(raw_clean, stim_channel=stim_ch, output='onset') epochs = mne.Epochs(raw, events, event_id=stim_event_ids, tmin=stim_tmin, tmax=stim_tmax, picks=mne.pick_types(raw.info, meg=True, exclude='bads')) evoked = epochs.average() epochs_clean = mne.Epochs(raw_clean, events_clean, event_id=stim_event_ids, tmin=stim_tmin, tmax=stim_tmax, picks=mne.pick_types(raw_clean.info, meg=True, exclude='bads')) evoked_clean = epochs_clean.average() stim_diff_signal = mne.combine_evoked([evoked, evoked_clean], weights=[1, -1]) if resp_ch: # stim related events resp_events = mne.find_events(raw, stim_channel=resp_ch, output='onset') resp_events_clean = mne.find_events(raw_clean, stim_channel=resp_ch, output='onset') resp_epochs = mne.Epochs(raw, resp_events, event_id=resp_event_ids, tmin=resp_tmin, tmax=resp_tmax, picks=mne.pick_types(raw.info, meg=True, exclude='bads')) resp_evoked = resp_epochs.average() resp_epochs_clean = mne.Epochs(raw_clean, resp_events_clean, event_id=resp_event_ids, tmin=resp_tmin, tmax=resp_tmax, picks=mne.pick_types(raw_clean.info, meg=True, exclude='bads')) resp_evoked_clean = resp_epochs_clean.average() resp_diff_signal = mne.combine_evoked([resp_evoked, resp_evoked_clean], weights=[1, -1]) # MEG signal around ECG events ecg_epochs = create_ecg_epochs(raw, ch_name=ecg_ch, event_id=ecg_id, picks=mne.pick_types(raw.info, meg=True, ecg=True, exclude=[ecg_ch]), tmin=ecg_tmin, tmax=ecg_tmax, l_freq=ecg_lfreq, h_freq=ecg_hfreq, preload=True, keep_ecg=False, baseline=(None, None)) ecg_clean_epochs = create_ecg_epochs(raw_clean, ch_name=ecg_ch, event_id=ecg_id, picks=mne.pick_types(raw.info, meg=True, ecg=True, exclude=[ecg_ch]), tmin=ecg_tmin, tmax=ecg_tmax, l_freq=ecg_lfreq, h_freq=ecg_hfreq, preload=True, keep_ecg=False, baseline=(None, None)) stim_diff_ecg = mne.combine_evoked([ecg_epochs.average(), ecg_clean_epochs.average()], weights=[1, -1]) # MEG signal around EOG1 events eog1_epochs = create_eog_epochs(raw, ch_name=eog1_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) eog1_clean_epochs = create_eog_epochs(raw_clean, ch_name=eog1_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) stim_diff_eog1 = mne.combine_evoked([eog1_epochs.average(), eog1_clean_epochs.average()], weights=[1, -1]) # MEG signal around EOG2 events eog2_epochs = create_eog_epochs(raw, ch_name=eog2_ch, event_id=998, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) eog2_clean_epochs = create_eog_epochs(raw_clean, ch_name=eog2_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) stim_diff_eog2 = mne.combine_evoked([eog2_epochs.average(), eog2_clean_epochs.average()], weights=[1, -1]) # plot the overview if resp_ch: nrows, ncols = 5, 2 fig = pl.figure('Overview', figsize=(10, 20)) else: nrows, ncols = 4, 2 fig = pl.figure('Overview', figsize=(10, 16)) ax1 = pl.subplot(nrows, ncols, 1) ax1.set_title('ECG - before (b) / after (r). %d events.' % len(ecg_epochs), fontdict=dict(fontsize='medium')) ecg_evoked = ecg_epochs.average() ecg_evoked_clean = ecg_clean_epochs.average() for i in range(len(ecg_evoked.data)): ax1.plot(ecg_evoked.times * 1e3, ecg_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(ecg_evoked_clean.data)): ax1.plot(ecg_evoked_clean.times * 1e3, ecg_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_ecg = dict(mag=ax1.get_ylim()) ax1.set_xlim(ecg_tmin * 1e3, ecg_tmax * 1e3) ax2 = pl.subplot(nrows, ncols, 2) stim_diff_ecg.plot(axes=ax2, ylim=ylim_ecg, titles=dict(mag='Difference')) ax3 = pl.subplot(nrows, ncols, 3) ax3.set_title('EOG (h) - before (b) / after (r). %d events.' % len(eog1_epochs), fontdict=dict(fontsize='medium')) eog1_evoked = eog1_epochs.average() eog1_evoked_clean = eog1_clean_epochs.average() for i in range(len(eog1_evoked.data)): ax3.plot(eog1_evoked.times * 1e3, eog1_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(eog1_evoked_clean.data)): ax3.plot(eog1_evoked_clean.times * 1e3, eog1_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_eog = dict(mag=ax3.get_ylim()) ax3.set_xlim(eog_tmin * 1e3, eog_tmax * 1e3) ax4 = pl.subplot(nrows, ncols, 4) stim_diff_eog1.plot(axes=ax4, ylim=ylim_eog, titles=dict(mag='Difference')) ax5 = pl.subplot(nrows, ncols, 5) ax5.set_title('EOG (v) - before (b) / after (r). %d events.' % len(eog2_epochs), fontdict=dict(fontsize='medium')) eog2_evoked = eog2_epochs.average() eog2_evoked_clean = eog2_clean_epochs.average() for i in range(len(eog2_evoked.data)): ax5.plot(eog2_evoked.times * 1e3, eog2_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(eog2_evoked_clean.data)): ax5.plot(eog2_evoked_clean.times * 1e3, eog2_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_eog = dict(mag=ax5.get_ylim()) ax5.set_xlim(eog_tmin * 1e3, eog_tmax * 1e3) ax6 = pl.subplot(nrows, ncols, 6) stim_diff_eog2.plot(axes=ax6, ylim=ylim_eog, titles=dict(mag='Difference')) # plot the signal + diff ax7 = pl.subplot(nrows, ncols, 7) ax7.set_title('MEG Signal around stim. %d events.' % len(epochs.events), fontdict=dict(fontsize='medium')) for i in range(len(evoked.data)): ax7.plot(evoked.times * 1e3, evoked.data[i] * 1e15, color='k', label='before') for j in range(len(evoked_clean.data)): ax7.plot(evoked_clean.times * 1e3, evoked_clean.data[j] * 1e15, color='r', label='after') ax7.set_xlim(stim_tmin * 1e3, stim_tmax * 1e3) ylim_diff = dict(mag=ax7.get_ylim()) ax8 = pl.subplot(nrows, ncols, 8) stim_diff_signal.plot(axes=ax8, ylim=ylim_diff, titles=dict(mag='Difference')) if resp_ch: # plot the signal + diff ax9 = pl.subplot(nrows, ncols, 9) ax9.set_title('MEG Signal around resp. %d events.' % len(resp_epochs.events), fontdict=dict(fontsize='medium')) for i in range(len(resp_evoked.data)): ax9.plot(resp_evoked.times * 1e3, resp_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(resp_evoked_clean.data)): ax9.plot(resp_evoked_clean.times * 1e3, resp_evoked_clean.data[j] * 1e15, color='r', label='after') ax9.set_xlim(resp_tmin * 1e3, resp_tmax * 1e3) ylim_diff = dict(mag=ax9.get_ylim()) ax10 = pl.subplot(nrows, ncols, 10) resp_diff_signal.plot(axes=ax10, ylim=ylim_diff, titles=dict(mag='Difference')) pl.tight_layout() pl.savefig(overview_fname) pl.close('all')
evoked_right.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 1], vmin=vmin, vmax=vmax, colorbar=False, **topomap_args) evoked_right.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 1], vmin=vmin, vmax=vmax, colorbar=False, **topomap_args) evoked_diff = mne.combine_evoked([evoked_left, -evoked_right], weights='equal') evoked_diff.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 2], vmin=vmin, vmax=vmax, **topomap_args) evoked_diff.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 2], vmin=vmin, vmax=vmax, colorbar=True, **topomap_args)
def plot_artefact_overview(raw_orig, raw_clean, stim_event_ids=[1], stim_ch='STI 014', resp_ch=None, resp_event_ids=None, ecg_ch='EEG 002', eog1_ch='EEG 001', eog2_ch='EEG 003', eog_tmin=-0.5, eog_tmax=0.5, eog_id=998, eog_lfreq=8., eog_hfreq=20., ecg_tmin=-0.5, ecg_tmax=0.5, ecg_id=999, ecg_lfreq=8., ecg_hfreq=20., stim_tmin=-0.2, stim_tmax=0.8, resp_tmin=-0.6, resp_tmax=0.4, eve_output='onset', overview_fname=None): ''' Plot an overview of the artefact rejection with ECG, EOG vertical and EOG horizontal channels. Shows the data before and after cleaning along with a difference plot. raw_orig: instance of mne.io.Raw | str File name of raw object of the uncleaned data. raw_clean: instance of mne.io.Raw | str File name of raw object of the cleaned data. stim_event_ids: list List of stim or resp event ids. Defaults to [1]. resp_event_ids: list List of stim or resp event ids. Defaults to None. eve_output: 'onset' | 'offset' | 'step' Whether to report when events start, when events end, or both. overview_fname: str | None Name to save the plot generated. (considers raw_clean.filenames[0]) Notes: Time is always shown in milliseconds (1e3) and the MEG data from mag is always in femtoTesla (fT) (1e15) ''' from mne.preprocessing import create_ecg_epochs, create_eog_epochs raw = check_read_raw(raw_orig, preload=True) raw_clean = check_read_raw(raw_clean, preload=True) if not overview_fname: try: overview_fname = raw_clean.filenames[0].rsplit('-raw.fif')[0] + ',overview-plot.png' except: overview_fname = 'overview-plot.png' # stim related events events = mne.find_events(raw, stim_channel=stim_ch, output='onset') events_clean = mne.find_events(raw_clean, stim_channel=stim_ch, output='onset') epochs = mne.Epochs(raw, events, event_id=stim_event_ids, tmin=stim_tmin, tmax=stim_tmax, picks=mne.pick_types(raw.info, meg=True, exclude='bads')) evoked = epochs.average() epochs_clean = mne.Epochs(raw_clean, events_clean, event_id=stim_event_ids, tmin=stim_tmin, tmax=stim_tmax, picks=mne.pick_types(raw_clean.info, meg=True, exclude='bads')) evoked_clean = epochs_clean.average() stim_diff_signal = mne.combine_evoked([evoked, evoked_clean], weights=[1, -1]) if resp_ch: # stim related events resp_events = mne.find_events(raw, stim_channel=resp_ch, output='onset') resp_events_clean = mne.find_events(raw_clean, stim_channel=resp_ch, output='onset') resp_epochs = mne.Epochs(raw, resp_events, event_id=resp_event_ids, tmin=resp_tmin, tmax=resp_tmax, picks=mne.pick_types(raw.info, meg=True, exclude='bads')) resp_evoked = resp_epochs.average() resp_epochs_clean = mne.Epochs(raw_clean, resp_events_clean, event_id=resp_event_ids, tmin=resp_tmin, tmax=resp_tmax, picks=mne.pick_types(raw_clean.info, meg=True, exclude='bads')) resp_evoked_clean = resp_epochs_clean.average() resp_diff_signal = mne.combine_evoked([resp_evoked, resp_evoked_clean], weights=[1, -1]) # MEG signal around ECG events ecg_epochs = create_ecg_epochs(raw, ch_name=ecg_ch, event_id=ecg_id, picks=mne.pick_types(raw.info, meg=True, ecg=True, exclude=[ecg_ch]), tmin=ecg_tmin, tmax=ecg_tmax, l_freq=ecg_lfreq, h_freq=ecg_hfreq, preload=True, keep_ecg=False, baseline=(None, None)) ecg_clean_epochs = create_ecg_epochs(raw_clean, ch_name=ecg_ch, event_id=ecg_id, picks=mne.pick_types(raw.info, meg=True, ecg=True, exclude=[ecg_ch]), tmin=ecg_tmin, tmax=ecg_tmax, l_freq=ecg_lfreq, h_freq=ecg_hfreq, preload=True, keep_ecg=False, baseline=(None, None)) stim_diff_ecg = mne.combine_evoked([ecg_epochs.average(), ecg_clean_epochs.average()], weights=[1, -1]) # MEG signal around EOG1 events eog1_epochs = create_eog_epochs(raw, ch_name=eog1_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) eog1_clean_epochs = create_eog_epochs(raw_clean, ch_name=eog1_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) stim_diff_eog1 = mne.combine_evoked([eog1_epochs.average(), eog1_clean_epochs.average()], weights=[1, -1]) # MEG signal around EOG2 events eog2_epochs = create_eog_epochs(raw, ch_name=eog2_ch, event_id=998, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) eog2_clean_epochs = create_eog_epochs(raw_clean, ch_name=eog2_ch, event_id=eog_id, picks=mne.pick_types(raw.info, meg=True, exclude='bads'), tmin=eog_tmin, tmax=eog_tmax, l_freq=eog_lfreq, h_freq=eog_hfreq, preload=True, baseline=(None, None)) stim_diff_eog2 = mne.combine_evoked([eog2_epochs.average(), eog2_clean_epochs.average()], weights=[1, -1]) # plot the overview if resp_ch: nrows, ncols = 5, 2 fig = plt.figure('Overview', figsize=(10, 20)) else: nrows, ncols = 4, 2 fig = plt.figure('Overview', figsize=(10, 16)) ax1 = plt.subplot(nrows, ncols, 1) ax1.set_title('ECG - before (b) / after (r). %d events.' % len(ecg_epochs), fontdict=dict(fontsize='medium')) ecg_evoked = ecg_epochs.average() ecg_evoked_clean = ecg_clean_epochs.average() for i in range(len(ecg_evoked.data)): ax1.plot(ecg_evoked.times * 1e3, ecg_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(ecg_evoked_clean.data)): ax1.plot(ecg_evoked_clean.times * 1e3, ecg_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_ecg = dict(mag=ax1.get_ylim()) ax1.set_xlim(ecg_tmin * 1e3, ecg_tmax * 1e3) ax2 = plt.subplot(nrows, ncols, 2) stim_diff_ecg.plot(axes=ax2, ylim=ylim_ecg, titles=dict(mag='Difference')) ax3 = plt.subplot(nrows, ncols, 3) ax3.set_title('EOG (h) - before (b) / after (r). %d events.' % len(eog1_epochs), fontdict=dict(fontsize='medium')) eog1_evoked = eog1_epochs.average() eog1_evoked_clean = eog1_clean_epochs.average() for i in range(len(eog1_evoked.data)): ax3.plot(eog1_evoked.times * 1e3, eog1_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(eog1_evoked_clean.data)): ax3.plot(eog1_evoked_clean.times * 1e3, eog1_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_eog = dict(mag=ax3.get_ylim()) ax3.set_xlim(eog_tmin * 1e3, eog_tmax * 1e3) ax4 = plt.subplot(nrows, ncols, 4) stim_diff_eog1.plot(axes=ax4, ylim=ylim_eog, titles=dict(mag='Difference')) ax5 = plt.subplot(nrows, ncols, 5) ax5.set_title('EOG (v) - before (b) / after (r). %d events.' % len(eog2_epochs), fontdict=dict(fontsize='medium')) eog2_evoked = eog2_epochs.average() eog2_evoked_clean = eog2_clean_epochs.average() for i in range(len(eog2_evoked.data)): ax5.plot(eog2_evoked.times * 1e3, eog2_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(eog2_evoked_clean.data)): ax5.plot(eog2_evoked_clean.times * 1e3, eog2_evoked_clean.data[j] * 1e15, color='r', label='after') ylim_eog = dict(mag=ax5.get_ylim()) ax5.set_xlim(eog_tmin * 1e3, eog_tmax * 1e3) ax6 = plt.subplot(nrows, ncols, 6) stim_diff_eog2.plot(axes=ax6, ylim=ylim_eog, titles=dict(mag='Difference')) # plot the signal + diff ax7 = plt.subplot(nrows, ncols, 7) ax7.set_title('MEG Signal around stim. %d events.' % len(epochs.events), fontdict=dict(fontsize='medium')) for i in range(len(evoked.data)): ax7.plot(evoked.times * 1e3, evoked.data[i] * 1e15, color='k', label='before') for j in range(len(evoked_clean.data)): ax7.plot(evoked_clean.times * 1e3, evoked_clean.data[j] * 1e15, color='r', label='after') ax7.set_xlim(stim_tmin * 1e3, stim_tmax * 1e3) ylim_diff = dict(mag=ax7.get_ylim()) ax8 = plt.subplot(nrows, ncols, 8) stim_diff_signal.plot(axes=ax8, ylim=ylim_diff, titles=dict(mag='Difference')) if resp_ch: # plot the signal + diff ax9 = plt.subplot(nrows, ncols, 9) ax9.set_title('MEG Signal around resp. %d events.' % len(resp_epochs.events), fontdict=dict(fontsize='medium')) for i in range(len(resp_evoked.data)): ax9.plot(resp_evoked.times * 1e3, resp_evoked.data[i] * 1e15, color='k', label='before') for j in range(len(resp_evoked_clean.data)): ax9.plot(resp_evoked_clean.times * 1e3, resp_evoked_clean.data[j] * 1e15, color='r', label='after') ax9.set_xlim(resp_tmin * 1e3, resp_tmax * 1e3) ylim_diff = dict(mag=ax9.get_ylim()) ax10 = plt.subplot(nrows, ncols, 10) resp_diff_signal.plot(axes=ax10, ylim=ylim_diff, titles=dict(mag='Difference')) plt.tight_layout() plt.savefig(overview_fname) plt.close('all')
# select the left-auditory condition event_id, tmin, tmax = 1, -0.2, 0.5 # create the mock-client object rt_client = MockRtClient(raw) # create the real-time epochs object rt_epochs = RtEpochs(rt_client, event_id, tmin, tmax, picks=picks, decim=1, reject=dict(grad=4000e-13, eog=150e-6)) # start the acquisition rt_epochs.start() # send raw buffers rt_client.send_data(rt_epochs, picks, tmin=0, tmax=150, buffer_size=1000) for ii, ev in enumerate(rt_epochs.iter_evoked()): print("Just got epoch %d" % (ii + 1)) ev.pick_types(meg=True, eog=False) # leave out the eog channel if ii == 0: evoked = ev else: evoked = mne.combine_evoked([evoked, ev], weights='nave') plt.clf() # clear canvas evoked.plot(axes=plt.gca(), time_unit='s') # plot on current figure plt.pause(0.05)
evoked_fname, condition='Left Auditory', baseline=(None, 0), proj=True) ############################################################################## # Or another one stored in the same file: evoked2 = mne.read_evokeds( evoked_fname, condition='Right Auditory', baseline=(None, 0), proj=True) ############################################################################## # Two evoked objects can be contrasted using :func:`mne.combine_evoked`. # This function can use ``weights='equal'``, which provides a simple # element-by-element subtraction (and sets the # ``mne.Evoked.nave`` attribute properly based on the underlying number # of trials) using either equivalent call: contrast = mne.combine_evoked([evoked1, evoked2], weights=[0.5, -0.5]) contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal') print(contrast) ############################################################################## # To do a weighted sum based on the number of averages, which will give # you what you would have gotten from pooling all trials together in # :class:`mne.Epochs` before creating the :class:`mne.Evoked` instance, # you can use ``weights='nave'``: average = mne.combine_evoked([evoked1, evoked2], weights='nave') print(contrast) ############################################################################## # Instead of dealing with mismatches in the number of averages, we can use # trial-count equalization before computing a contrast, which can have some
evokeds.append(evoked) evokeds_key[comment] = i end_i = i # Step 3: Make difference waves # Make contrast list contrasts = { 'oddball-standard': dict(conds=['oddball', 'standard'], weights=[1, -1]), 'top-bottom': dict(conds=['top', 'bottom'], weights=[1, -1]) } # Add in difference waves for contrast, v in contrasts.items(): cond_evokeds = [evokeds[evokeds_key[x]] for x in v['conds']] evoked = mne.combine_evoked(cond_evokeds, weights=v['weights']) evoked.comment = contrast evokeds.append(evoked) end_i += 1 evokeds_key[contrast] = end_i # Crop evokeds tmin = preprocess_options['evoked_tmin'], tmax = preprocess_options['evoked_tmax'] evokeds = [x.crop(tmin=tmin, tmax=tmax) for x in evokeds] # Step 4: write evokeds # Write evoked file evoked_fif_file = deriv_path / \ f'{sub}_task-{task}_ref-{ref}_lpf-none_ave.fif.gz' mne.write_evokeds(evoked_fif_file, evokeds)
reject=reject) epochs = mne.Epochs(raw, **epochs_params) print(epochs) ############################################################################### # Next, we create averages of stimulation-left vs stimulation-right trials. # We can use basic arithmetic to, for example, construct and plot # difference ERPs. left, right = epochs["left"].average(), epochs["right"].average() # create and plot difference ERP joint_kwargs = dict(ts_args=dict(time_unit='s'), topomap_args=dict(time_unit='s')) mne.combine_evoked([left, -right], weights='equal').plot_joint(**joint_kwargs) ############################################################################### # This is an equal-weighting difference. If you have imbalanced trial numbers, # you could also consider either equalizing the number of events per # condition (using # :meth:`epochs.equalize_event_counts <mne.Epochs.equalize_event_counts>`). # As an example, first, we create individual ERPs for each condition. aud_l = epochs["auditory", "left"].average() aud_r = epochs["auditory", "right"].average() vis_l = epochs["visual", "left"].average() vis_r = epochs["visual", "right"].average() all_evokeds = [aud_l, aud_r, vis_l, vis_r] print(all_evokeds)
# :meth:`~mne.Evoked.plot_topomap`. Here we'll examine just the EEG channels, # and see the classic auditory evoked N100-P200 pattern over dorso-frontal # electrodes, then plot scalp topographies at some additional arbitrary times: # sphinx_gallery_thumbnail_number = 13 aud_evoked.plot_joint(picks='eeg') aud_evoked.plot_topomap(times=[0., 0.08, 0.1, 0.12, 0.2], ch_type='eeg') ############################################################################## # Evoked objects can also be combined to show contrasts between conditions, # using the :func:`mne.combine_evoked` function. A simple difference can be # generated by negating one of the :class:`~mne.Evoked` objects passed into the # function. We'll then plot the difference wave at each sensor using # :meth:`~mne.Evoked.plot_topo`: evoked_diff = mne.combine_evoked([aud_evoked, -vis_evoked], weights='equal') evoked_diff.pick_types('mag').plot_topo(color='r', legend=False) ############################################################################## # Inverse modeling # ^^^^^^^^^^^^^^^^ # # Finally, we can estimate the origins of the evoked activity by projecting the # sensor data into this subject's :term:`source space` (a set of points either # on the cortical surface or within the cortical volume of that subject, as # estimated by structural MRI scans). MNE-Python supports lots of ways of doing # this (dynamic statistical parametric mapping, dipole fitting, beamformers, # etc.); here we'll use minimum-norm estimation (MNE) to generate a continuous # map of activation constrained to the cortical surface. MNE uses a linear # :term:`inverse operator` to project EEG+MEG sensor measurements into the # source space. The inverse operator is computed from the
which can be useful for reproducing research results. The MEGSIM files will be dowloaded automatically. The datasets are documented in: Aine CJ, Sanfratello L, Ranken D, Best E, MacArthur JA, Wallace T, Gilliam K, Donahue CH, Montano R, Bryant JE, Scott A, Stephen JM (2012) MEG-SIM: A Web Portal for Testing MEG Analysis Methods using Realistic Simulated and Empirical Data. Neuroinformatics 10:141-158 """ from mne import read_evokeds, combine_evoked from mne.datasets.megsim import load_data print(__doc__) condition = 'visual' # or 'auditory' or 'somatosensory' # Load experimental RAW files for the visual condition epochs_fnames = load_data(condition=condition, data_format='single-trial', data_type='simulation', verbose=True) # Take only 10 trials from the same simulation setup. epochs_fnames = [f for f in epochs_fnames if 'sim6_trial_' in f][:10] evokeds = [read_evokeds(f)[0] for f in epochs_fnames] mean_evoked = combine_evoked(evokeds, weights='nave') # Visualize the average mean_evoked.plot()
limo_epochs['Face/A'].average().plot_joint(times=[.15], title='Evoked response: Face A', ts_args=ts_args) limo_epochs['Face/B'].average().plot_joint(times=[.15], title='Evoked response: Face B', ts_args=ts_args) ############################################################################### # We can also compute the difference wave contrasting Face A and Face B. # Although, looking at the evoked responses above, we shouldn't expect great # differences among these face-stimuli. # # Compute difference wave (Face A minus Face B) difference_wave = mne.combine_evoked([limo_epochs['Face/A'].average(), -limo_epochs['Face/B'].average()], weights='equal') # Plot difference between Face A and Face B difference_wave.plot_joint(times=[.15], title='Difference Face A - Face B') ############################################################################### # As expected, no see clear differential patterns appears when contrasting # Face A and Face B. However, we could narrow our search to # since this is a "visual paradigm" it might be best to electrodes located over # the occipital lobe. After all this is "visual paradigm". Thus, differences # between stimuli (if any) might easier to spot over "more visual areas". # # Create a dictionary containing the evoked responses conditions = ["Face/A", "Face/B"] evoked_dict = dict()
# button press). You can view the topographies from a certain time span by # painting an area with clicking and holding the left mouse button. evoked_std.plot(window_title='Standard', gfp=True) evoked_dev.plot(window_title='Deviant', gfp=True) ############################################################################### # Show activations as topography figures. times = np.arange(0.05, 0.301, 0.025) evoked_std.plot_topomap(times=times, title='Standard') evoked_dev.plot_topomap(times=times, title='Deviant') ############################################################################### # We can see the MMN effect more clearly by looking at the difference between # the two conditions. P50 and N100 are no longer visible, but MMN/P200 and # P300 are emphasised. evoked_difference = combine_evoked([evoked_dev, evoked_std], weights=[1, -1]) evoked_difference.plot(window_title='Difference', gfp=True) ############################################################################### # Source estimation. # We compute the noise covariance matrix from the empty room measurement # and use it for the other runs. reject = dict(mag=4e-12) cov = mne.compute_raw_covariance(raw_erm, reject=reject) cov.plot(raw_erm.info) del raw_erm ############################################################################### # The transformation is read from a file. More information about coregistering # the data, see :ref:`ch_interactive_analysis` or # :func:`mne.gui.coregistration`.
# -*- coding: utf-8 -*- """ Created on Tue Aug 15 12:58:38 2017 @author: ning """ working_dir = 'D:\\Epochs\\' import os os.chdir(working_dir) import mne import numpy as np epochs = [] epoch = [mne.read_epochs('Ex10_Suj19_Run%d-epo.fif'% ii) for ii in np.arange(1,5)] epochs = mne.concatenate_epochs(epoch) old = epochs['after'].average() new_new = epochs['new'].average() new_old = epochs['before'].average() scramble = epochs['scramble'].average() mne.combine_evoked([old, -new_old],weights='equal').plot_joint(times=[0,.4,.8,1.2],title='old vs [11,21,31]') mne.combine_evoked([old, -new_new],weights='equal').plot_joint(times=[0,.4,.8,1.2],title='old vs new' ) mne.combine_evoked([old, -scramble],weights='equal').plot_joint(times=[0,.4,.8,1.2],title='old vs scramble') old.pick_channels(['PO8']).plot(titles='old') new_new.pick_channels(['PO8']).plot(titles='new')