def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data)
def test_lcmv(): """Test LCMV with evoked data and single trials """ raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() for fwd in [forward, forward_vol]: stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01) if fwd is forward: assert_true(isinstance(stc, SourceEstimate)) else: assert_true(isinstance(stc, VolSourceEstimate)) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.105) assert_true(1.9 < np.max(max_stc) < 3.) if fwd is forward: # Test picking normal orientation (surface source space only) stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal") stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.11) assert_true(1. < np.max(max_stc) < 2.) # The amplitude of normal orientation results should always be # smaller than free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, pick_ori="max-power") stc_pow = np.sum(stc_max_power.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc_max_power.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Maximum output source power orientation results should be similar to # free orientation results assert_true((stc_max_power.data - stc.data < 0.5).all()) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power") # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stcs[0].data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
############################################ # Calculate epochs src estimates ############################################ if inv_method == 'lcmv': ''' fake_noise_cov = FakeCov(subj_d[i]['epo'].get_data(), subj_d[i]['epo'].info) fake_data_cov = FakeCov(subj_d[i]['inv']['source_cov']['data'], subj_d[i]['inv']['info']) ''' noise_cov = mne.compute_covariance(subj_d[i]['epo'], tmin=-0.2, tmax=0) data_cov = mne.compute_covariance(subj_d[i]['epo'], tmin=0, tmax=4.5) stc_list = lcmv_epochs(subj_d[i]['epo'][p], subj_d[i]['fwd'], noise_cov, data_cov) #label=subj_d[i]['lab']) else: stc_list = inv_epochs(subj_d[i]['epo'][p], subj_d[i]['inv'], lambda2, inv_method, #label=subj_d[i]['lab'], verbose=False) ###################################################################### # Save each unprocessed stc file and compute/save morphed stc ###################################################################### for ti, temp_stc in enumerate(stc_list): # Save each unprocessed stc file save_fname = op.join(save_folder_unproc, subj_d[i]['Subj#'] + '_' + p + '_' + inv_method + '_t' + str(ti)) temp_stc.save(save_fname, verbose=False)
def test_lcmv(): """Test LCMV with evoked data and single trials.""" raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() for fwd in [forward, forward_vol]: stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, max_ori_out='signed') stc.crop(0.02, None) stc_pow = np.sum(np.abs(stc.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.105, tmax) assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc)) if fwd is forward: # Test picking normal orientation (surface source space only) stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal", max_ori_out='signed') stc_normal.crop(0.02, None) stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.04 < tmax < 0.11, tmax) assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc)) # The amplitude of normal orientation results should always be # smaller than free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') stc_max_power.crop(0.02, None) stc_pow = np.sum(np.abs(stc_max_power.data), axis=1) idx = np.argmax(stc_pow) max_stc = np.abs(stc_max_power.data[idx]) tmax = stc.times[np.argmax(max_stc)] assert_true(0.08 < tmax < 0.11, tmax) assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc)) stc_max_power.data[:, :] = np.abs(stc_max_power.data) if fwd is forward: # Maximum output source power orientation results should be # similar to free orientation results in areas with channel # coverage label = mne.read_label(fname_label) mean_stc = stc.extract_label_time_course(label, fwd['src'], mode='mean') mean_stc_max_pow = \ stc_max_power.extract_label_time_course(label, fwd['src'], mode='mean') assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all()) # Test NAI weight normalization: stc_nai = lcmv(evoked, fwd, noise_cov=noise_cov, data_cov=data_cov, reg=0.01, pick_ori='max-power', weight_norm='nai', max_ori_out='signed') stc_nai.crop(0.02, None) # Test whether unit-noise-gain solution is a scaled version of NAI pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)), np.concatenate(stc_max_power.data)) assert_almost_equal(pearsoncorr[0, 1], 1.) # Test sphere head model with unit-noise gain beamformer and orientation # selection and rank reduction of the leadfield sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080) src = mne.setup_volume_source_space(subject=None, pos=15., mri=None, sphere=(0.0, 0.0, 0.0, 80.0), bem=None, mindist=5.0, exclude=2.0) fwd_sphere = mne.make_forward_solution(evoked.info, trans=None, src=src, bem=sphere, eeg=False, meg=True) # Test that we get an error is not reducing rank assert_raises(ValueError, lcmv, evoked, fwd_sphere, noise_cov, data_cov, reg=0.1, weight_norm='unit-noise-gain', pick_ori="max-power", reduce_rank=False) # Now let's reduce it stc_sphere = lcmv(evoked, fwd_sphere, noise_cov, data_cov, reg=0.1, weight_norm='unit-noise-gain', pick_ori="max-power", reduce_rank=True, max_ori_out='signed') stc_sphere = np.abs(stc_sphere) stc_sphere.crop(0.02, None) stc_pow = np.sum(stc_sphere.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc_sphere.data[idx] tmax = stc_sphere.times[np.argmax(max_stc)] assert_true(0.08 < tmax < 0.11, tmax) assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc)) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if missing of data covariance matrix is detected assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=noise_cov, data_cov=None, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=None, data_cov=data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if not-yet-implemented orientation selections raise error with # neural activity index assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal", weight_norm='nai') assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori=None, weight_norm='nai') # Test if no weight-normalization and max-power source orientation throw # an error assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="max-power", weight_norm=None, max_ori_out='signed') # Test if wrong channel selection is detected in application of filter evoked_ch = deepcopy(evoked) evoked_ch.pick_channels(evoked_ch.ch_names[:-1]) filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01, noise_cov=noise_cov) assert_raises(ValueError, apply_lcmv, evoked_ch, filters, max_ori_out='signed') # Test if non-matching SSP projection is detected in application of filter raw_proj = deepcopy(raw) raw_proj.del_proj() assert_raises(ValueError, apply_lcmv_raw, raw_proj, filters, max_ori_out='signed') # Test if setting reduce_rank to True returns a NotImplementedError # when no orientation selection is done or pick_ori='normal' assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, pick_ori=None, weight_norm='nai', reduce_rank=True, max_ori_out='signed') assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori, noise_cov, data_cov, pick_ori='normal', weight_norm='nai', reduce_rank=True, max_ori_out='signed') # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, max_ori_out='signed') stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True, max_ori_out='signed') assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) epochs.drop_bad() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stcs[0].data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01, max_ori_out='signed') assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label, max_ori_out='signed') assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
def test_lcmv(): """Test LCMV with evoked data and single trials.""" raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() for fwd in [forward, forward_vol]: stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, max_ori_out='signed') stc.crop(0.02, None) stc_pow = np.sum(np.abs(stc.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.105, tmax) assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc)) if fwd is forward: # Test picking normal orientation (surface source space only) stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal", max_ori_out='signed') stc_normal.crop(0.02, None) stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.04 < tmax < 0.11, tmax) assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc)) # The amplitude of normal orientation results should always be # smaller than free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') stc_max_power.crop(0.02, None) stc_pow = np.sum(np.abs(stc_max_power.data), axis=1) idx = np.argmax(stc_pow) max_stc = np.abs(stc_max_power.data[idx]) tmax = stc.times[np.argmax(max_stc)] assert_true(0.08 < tmax < 0.11, tmax) assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc)) stc_max_power.data[:, :] = np.abs(stc_max_power.data) if fwd is forward: # Maximum output source power orientation results should be # similar to free orientation results in areas with channel # coverage label = mne.read_label(fname_label) mean_stc = stc.extract_label_time_course(label, fwd['src'], mode='mean') mean_stc_max_pow = \ stc_max_power.extract_label_time_course(label, fwd['src'], mode='mean') assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all()) # Test NAI weight normalization: stc_nai = lcmv(evoked, fwd, noise_cov=noise_cov, data_cov=data_cov, reg=0.01, pick_ori='max-power', weight_norm='nai', max_ori_out='signed') stc_nai.crop(0.02, None) # Test whether unit-noise-gain solution is a scaled version of NAI pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)), np.concatenate(stc_max_power.data)) assert_almost_equal(pearsoncorr[0, 1], 1.) # Test sphere head model with unit-noise gain beamformer and orientation # selection and rank reduction of the leadfield sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080) src = mne.setup_volume_source_space(subject=None, pos=15., mri=None, sphere=(0.0, 0.0, 0.0, 80.0), bem=None, mindist=5.0, exclude=2.0) fwd_sphere = mne.make_forward_solution(evoked.info, trans=None, src=src, bem=sphere, eeg=False, meg=True) # Test that we get an error is not reducing rank assert_raises(ValueError, lcmv, evoked, fwd_sphere, noise_cov, data_cov, reg=0.1, weight_norm='unit-noise-gain', pick_ori="max-power", reduce_rank=False) # Now let's reduce it stc_sphere = lcmv(evoked, fwd_sphere, noise_cov, data_cov, reg=0.1, weight_norm='unit-noise-gain', pick_ori="max-power", reduce_rank=True, max_ori_out='signed') stc_sphere = np.abs(stc_sphere) stc_sphere.crop(0.02, None) stc_pow = np.sum(stc_sphere.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc_sphere.data[idx] tmax = stc_sphere.times[np.argmax(max_stc)] assert_true(0.08 < tmax < 0.11, tmax) assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc)) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if missing of data covariance matrix is detected assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=noise_cov, data_cov=None, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=None, data_cov=data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if not-yet-implemented orientation selections raise error with # neural activity index assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal", weight_norm='nai') assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori=None, weight_norm='nai') # Test if no weight-normalization and max-power source orientation throw # an error assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="max-power", weight_norm=None, max_ori_out='signed') # Test if wrong channel selection is detected in application of filter evoked_ch = deepcopy(evoked) evoked_ch.pick_channels(evoked_ch.ch_names[1:]) filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01, noise_cov=noise_cov) assert_raises(ValueError, apply_lcmv, evoked_ch, filters, max_ori_out='signed') # Test if discrepancies in channel selection of data and fwd model are # handled correctly in apply_lcmv # make filter with data where first channel was removed filters = make_lcmv(evoked_ch.info, forward_vol, data_cov, reg=0.01, noise_cov=noise_cov) # applying that filter to the full data set should automatically exclude # this channel from the data stc = apply_lcmv(evoked, filters, max_ori_out='signed') # the result should be equal to applying this filter to a dataset without # this channel: stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed') assert_array_almost_equal(stc.data, stc_ch.data) # Test if non-matching SSP projection is detected in application of filter raw_proj = deepcopy(raw) raw_proj.del_proj() assert_raises(ValueError, apply_lcmv_raw, raw_proj, filters, max_ori_out='signed') # Test if setting reduce_rank to True returns a NotImplementedError # when no orientation selection is done or pick_ori='normal' assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, pick_ori=None, weight_norm='nai', reduce_rank=True, max_ori_out='signed') assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori, noise_cov, data_cov, pick_ori='normal', weight_norm='nai', reduce_rank=True, max_ori_out='signed') # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, max_ori_out='signed') stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True, max_ori_out='signed') assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) epochs.drop_bad() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stcs[0].data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01, max_ori_out='signed') assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label, max_ori_out='signed') assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Test picking normal orientation stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal") stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.11) assert_true(1. < np.max(max_stc) < 2.) # The amplitude of normal orientation results should always be smaller than # free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="max-power") stc_pow = np.sum(stc_max_power.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc_max_power.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Maximum output source power orientation results should be similar to free # orientation results assert_true((stc_max_power.data - stc.data < 0.5).all()) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power") # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, stcs_.next().data) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
def test_lcmv(): """Test LCMV with evoked data and single trials.""" raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() for fwd in [forward, forward_vol]: stc = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, max_ori_out='signed') stc.crop(0.02, None) stc_pow = np.sum(np.abs(stc.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.105, tmax) assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc)) if fwd is forward: # Test picking normal orientation (surface source space only) stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal") stc_normal.crop(0.02, None) stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.04 < tmax < 0.11, tmax) assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc)) # The amplitude of normal orientation results should always be # smaller than free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, fwd, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') stc_max_power.crop(0.02, None) stc_pow = np.sum(np.abs(stc_max_power.data), axis=1) idx = np.argmax(stc_pow) max_stc = np.abs(stc_max_power.data[idx]) tmax = stc.times[np.argmax(max_stc)] assert_true(0.08 < tmax < 0.11, tmax) assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc)) stc_max_power.data[:, :] = np.abs(stc_max_power.data) if fwd is forward: # Maximum output source power orientation results should be # similar to free orientation results in areas with channel # coverage label = mne.read_label(fname_label) mean_stc = stc.extract_label_time_course(label, fwd['src'], mode='mean') mean_stc_max_pow = \ stc_max_power.extract_label_time_course(label, fwd['src'], mode='mean') assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all()) # Test NAI weight normalization: stc_nai = lcmv(evoked, fwd, noise_cov=noise_cov, data_cov=data_cov, reg=0.01, pick_ori='max-power', weight_norm='nai', max_ori_out='signed') stc_nai.crop(0.02, None) # Test whether unit-noise-gain solution is a scaled version of NAI pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)), np.concatenate(stc_max_power.data)) assert_almost_equal(pearsoncorr[0, 1], 1.) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if missing of data covariance matrix is detected assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=noise_cov, data_cov=None, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov=None, data_cov=data_cov, reg=0.01, pick_ori="max-power", max_ori_out='signed') # Test if not-yet-implemented orientation selections raise error with # neural activity index assert_raises(NotImplementedError, lcmv, evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal", weight_norm='nai') assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori=None, weight_norm='nai') # Test if no weight-normalization and max-power source orientation throw # an error assert_raises(NotImplementedError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="max-power", weight_norm=None, max_ori_out='signed') # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) epochs.drop_bad() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stcs[0].data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
# Setup inverse model epochs.pick_types(meg=True, ref_meg=False) inv = make_inverse_operator(epochs.info, fwd, noise_cov, loose=0.2, depth=0.8) epochs.pick_types(meg=True, ref_meg=False) method = 'beamformer' # use of beamformer method # reconstruct source signal at the single trial data_cov = mne.compute_covariance(epochs, tmin=0.04, method='shrunk') stcs = lcmv_epochs(epochs, fwd, noise_cov=noise_cov, data_cov=data_cov, reg=0.05, pick_ori='max-power') n_times = len(epochs.times) n_vertices = len(stcs[0].data) n_epochs = len(epochs.events) X = np.zeros([n_epochs, n_vertices, n_times]) for jj, stc in enumerate(stcs): X[jj] = stc.data # Loop across each analysis for analysis in epoch_analyses: # define to-be-predicted values y = np.array(events[analysis]) # Define estimators depending on the analysis if ('cue_side' in analysis or 'cue_type' in analysis):
def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, stcs_.next().data) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)