def test_lcmv_raw(): """Test LCMV with raw data.""" raw, _, _, _, noise_cov, label, forward, _, _, _ =\ _get_data(all_forward=False, epochs=False, data_cov=False) tmin, tmax = 0, 20 start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV data_cov = mne.compute_raw_covariance(raw, tmin=tmin, tmax=tmax) filters = make_lcmv(raw.info, forward, data_cov, reg=0.01, noise_cov=noise_cov, label=label) stc = apply_lcmv_raw(raw, filters, start=start, stop=stop, max_ori_out='signed') assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert len(stc.vertices[0]) == len( np.intersect1d(vertno[0], label.vertices)) assert len(stc.vertices[1]) == 0
def _update(self): t1 = time.time() input_array = self.input_node.output raw_array = mne.io.RawArray(input_array, self._mne_info, verbose='ERROR') raw_array.pick_types(eeg=True, meg=False, stim=False, exclude='bads') raw_array.set_eeg_reference(ref_channels='average', projection=True) t2 = time.time() self.logger.debug('Prepare arrays in {:.1f} ms'.format( (t2 - t1) * 1000)) if self.is_adaptive: self._update_covariance_matrix(input_array) t1 = time.time() self._filters = make_lcmv(info=self._mne_info, forward=self.fwd_surf, data_cov=self._Rxx, reg=0.5, pick_ori='max-power', weight_norm='unit-noise-gain', reduce_rank=False) t2 = time.time() self.logger.debug('Assembled lcmv instance in {:.1f} ms'.format( (t2 - t1) * 1000)) self._filters['source_nn'] = [] t1 = time.time() stc = apply_lcmv_raw(raw=raw_array, filters=self._filters, max_ori_out='signed') t2 = time.time() self.logger.debug('Applied lcmv inverse in {:.1f} ms'.format( (t2 - t1) * 1000)) output = stc.data t1 = time.time() if self.fixed_orientation is True: if self.output_type == 'power': output = output**2 else: vertex_count = self.fwd_surf['nsource'] output = np.sum(np.power(output, 2).reshape((vertex_count, 3, -1)), axis=1) if self.output_type == 'activation': output = np.sqrt(output) self.output = output t2 = time.time() self.logger.debug('Finalized in {:.1f} ms'.format((t2 - t1) * 1000))
def test_lcmv_raw(): """Test LCMV with raw data.""" raw, _, _, _, noise_cov, label, forward, _, _, _ =\ _get_data(all_forward=False, epochs=False, data_cov=False) tmin, tmax = 0, 20 start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV data_cov = mne.compute_raw_covariance(raw, tmin=tmin, tmax=tmax) filters = make_lcmv(raw.info, forward, data_cov, reg=0.01, noise_cov=noise_cov, label=label) stc = apply_lcmv_raw(raw, filters, start=start, stop=stop, max_ori_out='signed') assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert len(stc.vertices[0]) == len(np.intersect1d(vertno[0], label.vertices)) assert len(stc.vertices[1]) == 0
def test_make_lcmv(tmpdir, reg, proj): """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(proj=proj) for fwd in [forward, forward_vol]: filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov) stc = apply_lcmv(evoked, filters, 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 0.08 < tmax < 0.15, tmax assert 0.9 < np.max(max_stc) < 3.5, np.max(max_stc) if fwd is forward: # Test picking normal orientation (surface source space only). filters = make_lcmv(evoked.info, forward_surf_ori, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='normal', weight_norm=None) stc_normal = apply_lcmv(evoked, filters, 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)] lower = 0.04 if proj else 0.025 assert lower < tmax < 0.14, tmax lower = 3e-7 if proj else 2e-7 assert lower < np.max(max_stc) < 3e-6, np.max(max_stc) # No weight normalization was applied, so the amplitude of normal # orientation results should always be smaller than free # orientation results. assert (np.abs(stc_normal.data) <= stc.data).all() # Test picking source orientation maximizing output source power filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='max-power') stc_max_power = apply_lcmv(evoked, filters, 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)] lower = 0.08 if proj else 0.04 assert lower < tmax < 0.15, tmax assert 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_array_less(np.abs(mean_stc - mean_stc_max_pow), 1.0) # Test NAI weight normalization: filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='max-power', weight_norm='nai') stc_nai = apply_lcmv(evoked, filters, 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 spatial filter contains src_type assert 'src_type' in filters # __repr__ assert len(evoked.ch_names) == 22 assert len(evoked.info['projs']) == (3 if proj else 0) assert len(evoked.info['bads']) == 2 rank = 17 if proj else 20 assert 'LCMV' in repr(filters) assert 'unknown subject' not in repr(filters) assert '4157 vert' in repr(filters) assert '20 ch' in repr(filters) assert 'rank %s' % rank in repr(filters) # I/O fname = op.join(str(tmpdir), 'filters.h5') with pytest.warns(RuntimeWarning, match='-lcmv.h5'): filters.save(fname) filters_read = read_beamformer(fname) assert isinstance(filters, Beamformer) assert isinstance(filters_read, Beamformer) # deal with object_diff strictness filters_read['rank'] = int(filters_read['rank']) filters['rank'] = int(filters['rank']) assert object_diff(filters, filters_read) == '' # Test if fixed forward operator is detected when picking normal or # max-power orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='max-power') # Test if non-surface oriented forward operator is detected when picking # normal orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') # Test if volume forward operator is detected when picking normal # orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov=data_cov, reg=0.01, noise_cov=None, pick_ori='max-power') # 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) pytest.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 # also test here that no warnings are thrown - implemented to check whether # src should not be None warning occurs with pytest.warns(None) as w: stc = apply_lcmv(evoked, filters, max_ori_out='signed') assert len(w) == 0 # 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 if proj: raw_proj = deepcopy(raw) raw_proj.del_proj() with pytest.raises(ValueError, match='do not match the projections'): apply_lcmv_raw(raw_proj, filters, max_ori_out='signed') # Test if spatial filter contains src_type assert 'src_type' in filters # check whether a filters object without src_type throws expected warning del filters['src_type'] # emulate 0.16 behaviour to cause warning with pytest.warns(RuntimeWarning, match='spatial filter does not contain ' 'src_type'): apply_lcmv(evoked, filters, max_ori_out='signed') # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov) stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed') stcs_ = apply_lcmv_epochs(epochs, filters, return_generator=True, max_ori_out='signed') assert_array_equal(stcs[0].data, next(stcs_).data) epochs.drop_bad() assert (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 filters = make_lcmv(evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov) stc_fixed = apply_lcmv(evoked, filters, 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 filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, label=label) stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed') assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data) # Test condition where the filters weights are zero. There should not be # any divide-by-zero errors zero_cov = data_cov.copy() zero_cov['data'][:] = 0 filters = make_lcmv(epochs.info, forward_fixed, zero_cov, reg=0.01, noise_cov=noise_cov) assert_array_equal(filters['weights'], 0) # Test condition where one channel type is picked # (avoid "grad data rank (13) did not match the noise rank (None)") data_cov_grad = pick_channels_cov( data_cov, [ch_name for ch_name in epochs.info['ch_names'] if ch_name.endswith(('2', '3'))]) assert len(data_cov_grad['names']) > 4 make_lcmv(epochs.info, forward_fixed, data_cov_grad, reg=0.01, noise_cov=noise_cov)
def _compute_LCMV_inverse_solution(raw_filename, sbj_id, subjects_dir, fwd_filename, cov_fname, parc='aparc', all_src_space=False, ROIs_mean=True, is_fixed=False): """ Compute the inverse solution on raw data by LCMV and return the average time series computed in the N_r regions of the source space defined by the specified cortical parcellation Inputs raw_filename : str filename of the raw data sbj_id : str subject name subjects_dir : str Freesurfer directory fwd_filename : str filename of the forward operator cov_filename : str filename of the noise covariance matrix parc: str the parcellation defining the ROIs atlas in the source space all_src_space: bool if True we compute the inverse for all points of the s0urce space ROIs_mean: bool if True we compute the mean of estimated time series on ROIs Outputs ts_file : str filename of the file where are saved the estimated time series labels_file : str filename of the file where are saved the ROIs of the parcellation label_names_file : str filename of the file where are saved the name of the ROIs of the parcellation label_coords_file : str filename of the file where are saved the coordinates of the centroid of the ROIs of the parcellation """ print(('\n*** READ raw filename %s ***\n' % raw_filename)) raw = read_raw_fif(raw_filename, preload=True) subj_path, basename, ext = split_f(raw_filename) print(('\n*** READ noise covariance %s ***\n' % cov_fname)) noise_cov = mne.read_cov(cov_fname) print(('\n*** READ FWD SOL %s ***\n' % fwd_filename)) forward = mne.read_forward_solution(fwd_filename) forward = mne.convert_forward_solution(forward, surf_ori=True) # compute data covariance matrix # reject = _create_reject_dict(raw.info) picks = pick_types(raw.info, meg=True, ref_meg=False, exclude='bads') data_cov = mne.compute_raw_covariance(raw, picks=picks) # compute LCMV filters filters = make_lcmv(raw.info, forward, data_cov, reg=0.05, noise_cov=noise_cov, pick_ori='normal', weight_norm='nai', depth=0.8) # apply spatial filter stc = apply_lcmv_raw(raw, filters, max_ori_out='signed') ts_file, label_ts, labels_file, label_names_file, label_coords_file = \ _process_stc(stc, basename, sbj_id, subjects_dir, parc, forward, False, is_fixed, all_src_space=False, ROIs_mean=True) return ts_file, labels_file, label_names_file, \ label_coords_file
def run_correlation(subjects_dir, subject, volume_spacing, freq, ortho_bool): num_threads(8) ortho_flag = str(ortho_bool) frequency = str(freq) DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files') eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz' eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz' fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif' t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz') heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz' fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd.fif.gz' src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src.fif.gz' cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}.fif.gz' raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}.fif.gz' raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj.fif.gz' source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl' corr_file_acLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acLeft.npy' corr_file_scLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scLeft.npy' corr_file_vcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcLeft.npy' corr_file_mtLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtLeft.npy' corr_file_mtlLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlLeft.npy' corr_file_smcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcLeft.npy' corr_file_lpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcLeft.npy' corr_file_dpfcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcLeft.npy' corr_file_tmpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcLeft.npy' corr_file_acRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acRight.npy' corr_file_scRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scRight.npy' corr_file_vcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcRight.npy' corr_file_mtRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtRight.npy' corr_file_mtlRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlRight.npy' corr_file_smcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcRight.npy' corr_file_lpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcRight.npy' corr_file_dpfcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcRight.npy' corr_file_tmpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcRight.npy' corr_file_mpfc = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mpfc.npy' corr_file_sma = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_sma.npy' check_for_files = [] check_for_files.append(corr_file_acLeft) check_for_files.append(corr_file_scLeft) check_for_files.append(corr_file_vcLeft) check_for_files.append(corr_file_mtLeft) check_for_files.append(corr_file_mtlLeft) check_for_files.append(corr_file_smcLeft) check_for_files.append(corr_file_lpcLeft) check_for_files.append(corr_file_dpfcLeft) check_for_files.append(corr_file_tmpcLeft) check_for_files.append(corr_file_acRight) check_for_files.append(corr_file_scRight) check_for_files.append(corr_file_vcRight) check_for_files.append(corr_file_mtRight) check_for_files.append(corr_file_mtlRight) check_for_files.append(corr_file_smcRight) check_for_files.append(corr_file_lpcRight) check_for_files.append(corr_file_dpfcRight) check_for_files.append(corr_file_tmpcRight) check_for_files.append(corr_file_mpfc) check_for_files.append(corr_file_sma) file_exist = [f for f in check_for_files if os.path.isfile(f)] file_not_exist = list(set(file_exist) ^ set(check_for_files)) if not file_not_exist: print('SC, AC, VC correlation files exists...') else: trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration file_trans = pathlib.Path(trans) file_ss = pathlib.Path(src_fname) file_fm = pathlib.Path(fwd_fname) file_proj = pathlib.Path(raw_proj) file_cov = pathlib.Path(cov_fname) file_rawcov = pathlib.Path(raw_cov_fname) t1 = nib.load(t1_fname) if not file_trans.exists(): print (f'{trans} File doesnt exist...') sys.exit(0) #info = mne.io.read_info(fname_meg) # plot_registration(info, trans, subject, subjects_dir) if not file_ss.exists(): src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', volume_spacing=volume_spacing) seed_l_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Left']) seed_r_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Right']) seed_l_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Left']) seed_r_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Right']) seed_l_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Left']) seed_r_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Right']) seed_l_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Left']) seed_r_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Right']) seed_l_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Left']) seed_r_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Right']) seed_l_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Left']) seed_r_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Right']) seed_l_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Left']) seed_r_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Right']) seed_l_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Left']) seed_r_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Right']) seed_l_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Left']) seed_r_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Right']) seed_mpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MPFC_MidBrain']) seed_sma = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMA_MidBrain']) src_inuse = np.where(src[0]['inuse'] == 1) loc_l_sc = src_inuse[0][0] loc_r_sc = src_inuse[0][1] loc_l_ac = src_inuse[0][2] loc_r_ac = src_inuse[0][3] loc_l_vc = src_inuse[0][4] loc_r_vc = src_inuse[0][5] loc_l_mt = src_inuse[0][6] loc_r_mt = src_inuse[0][7] loc_l_mtl = src_inuse[0][8] loc_r_mtl = src_inuse[0][9] loc_l_smc = src_inuse[0][10] loc_r_smc = src_inuse[0][11] loc_l_lpc = src_inuse[0][12] loc_r_lpc = src_inuse[0][13] loc_l_dpfc = src_inuse[0][14] loc_r_dpfc = src_inuse[0][15] loc_l_tmpc = src_inuse[0][16] loc_r_tmpc = src_inuse[0][17] loc_mpfc = src_inuse[0][18] loc_sma = src_inuse[0][19] src[0]['rr'][loc_l_sc] = seed_l_sc src[0]['rr'][loc_r_sc] = seed_r_sc src[0]['rr'][loc_l_ac] = seed_l_ac src[0]['rr'][loc_r_ac] = seed_r_ac src[0]['rr'][loc_l_vc] = seed_l_vc src[0]['rr'][loc_r_vc] = seed_r_vc src[0]['rr'][loc_l_mt] = seed_l_mt src[0]['rr'][loc_r_mt] = seed_r_mt src[0]['rr'][loc_l_mtl] = seed_l_mtl src[0]['rr'][loc_r_mtl] = seed_r_mtl src[0]['rr'][loc_l_smc] = seed_l_smc src[0]['rr'][loc_r_smc] = seed_r_smc src[0]['rr'][loc_l_lpc] = seed_l_lpc src[0]['rr'][loc_r_lpc] = seed_r_lpc src[0]['rr'][loc_l_dpfc] = seed_l_dpfc src[0]['rr'][loc_r_dpfc] = seed_r_dpfc src[0]['rr'][loc_l_tmpc] = seed_l_tmpc src[0]['rr'][loc_r_tmpc] = seed_r_tmpc src[0]['rr'][loc_mpfc] = seed_mpfc src[0]['rr'][loc_sma] = seed_sma src.save(src_fname, overwrite=True) src = mne.read_source_spaces(src_fname) #view_SS_brain(subject, subjects_dir, src) if not file_fm.exists(): forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname) fwd = mne.read_forward_solution(fwd_fname) # sensitivty_plot(subject, subjects_dir, fwd) raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True) srate = raw.info['sfreq'] n_time_samps = raw.n_times time_secs = raw.times ch_names = raw.ch_names n_chan = len(ch_names) freq_res = srate/n_time_samps print('\n') print('-------------------------- Data summary-------------------------------') print(f'Subject {subject}') print(f"Frequency resolution {freq_res} Hz") print(f"The first few channel names are {ch_names[:3]}") print(f"The last time sample at {time_secs[-1]} seconds.") print(f"Sampling Frequency (No of time points/sec) {srate} Hz") print(f"Miscellaneous acquisition info {raw.info['description']}") print(f"Bad channels marked during data acquisition {raw.info['bads']}") print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.") print('------------------------------------------------------------------------') print('\n') # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True) if not file_proj.exists(): projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063') projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061') projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062') if projs_ecg is not None: mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors raw.info['projs'] += projs_ecg if projs_eog1 is not None: mne.write_proj(eye_proj1, projs_eog1) raw.info['projs'] += projs_eog1 if projs_eog2 is not None: mne.write_proj(eye_proj2, projs_eog2) raw.info['projs'] += projs_eog2 raw.apply_proj() raw.save(raw_proj, proj=True, overwrite=True) print(raw_proj) raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True) print(f'High-pass filtering data at 0.5 Hz') raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir') if not file_cov.exists(): cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest mne.write_cov(cov_fname, cov) cov = mne.read_cov(cov_fname) # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False # raw_proj_applied.crop(tmax=10) do_epochs = False l_freq = freq-2.0 h_freq = freq+2.0 print(f'Band pass filter data [{l_freq}, {h_freq}]') raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq) if do_epochs: print('Segmenting raw data...') events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.) raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5., baseline=None, preload=True) data_cov = mne.compute_covariance(raw_proj_filtered) else: if not file_rawcov.exists(): data_cov = mne.compute_raw_covariance(raw_proj_filtered) mne.write_cov(raw_cov_fname, data_cov) else: data_cov = mne.read_cov(file_rawcov) filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert() if do_epochs: stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False) else: stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True) stcs = [stcs] # Power Envelope Correlation print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize {ortho_flag}') all_corr = envelope_correlation(stcs, combine=None, orthogonalize=False, log=False, absolute=True, verbose=None) np.save(corr_file_scLeft, all_corr[seed_left_sc]) np.save(corr_file_acLeft, all_corr[seed_left_ac]) np.save(corr_file_vcLeft, all_corr[seed_left_vc]) np.save(corr_file_mtLeft, all_corr[seed_left_mt]) np.save(corr_file_mtlLeft, all_corr[seed_left_mtl]) np.save(corr_file_smcLeft, all_corr[seed_left_smc]) np.save(corr_file_lpcLeft, all_corr[seed_left_lpc]) np.save(corr_file_dpfcLeft, all_corr[seed_left_dpfc]) np.save(corr_file_tmpcLeft, all_corr[seed_left_tmpc]) np.save(corr_file_scRight, all_corr[seed_right_sc]) np.save(corr_file_acRight, all_corr[seed_right_ac]) np.save(corr_file_vcRight, all_corr[seed_right_vc]) np.save(corr_file_mtRight, all_corr[seed_right_mt]) np.save(corr_file_mtlRight, all_corr[seed_right_mtl]) np.save(corr_file_smcRight, all_corr[seed_right_smc]) np.save(corr_file_lpcRight, all_corr[seed_right_lpc]) np.save(corr_file_dpfcRight, all_corr[seed_right_dpfc]) np.save(corr_file_tmpcRight, all_corr[seed_right_tmpc]) np.save(corr_file_mpfc, all_corr[seed_mpfc_index]) np.save(corr_file_sma, all_corr[seed_sma_index]) del stcs
ch_names.append('UPPT001') raw.pick_types(meg=True, eeg=False) if source_method == 'beamformer': for label in labels: print label.name filters = make_lcmv(raw.info, fwd, data_cov, reg=0.05, noise_cov=noise_cov, label=label, pick_ori=None, weight_norm='unit-noise-gain') # Apply lcmv on evoked and raw data evoked_stc = apply_lcmv(evoked, filters) raw_stc = apply_lcmv_raw(raw, filters) ch_names.append(label.name) evoked_stcs.append(evoked_stc.data.mean(0)) raw_stcs.append(raw_stc.data.mean(0)) evoked_stcs = np.array(evoked_stcs) raw_stcs = np.array(raw_stcs) else: # Setup inverse model ---------------------------------------------------- inv = make_inverse_operator(epochs.info, fwd, noise_cov, loose=0.2, depth=0.8) snr_evoked = 3.0 snr_raw = 1.0 for label in labels:
# beamformer requirements bem = op.join(subjects_dir, subject, 'bem', 'genz501_17a-5120-bem-sol.fif') sphere = mne.make_sphere_model(r0='auto', head_radius='auto', info=raw_filt.info) src = mne.setup_volume_source_space(subject='fsaverage', bem=bem, mri=op.join(subjects_dir, 'fsaverage', 'mri', 'T1.mgz') subjects_dir=subjects_dir) fwd = mne.make_forward_solution(raw_filt.info, trans=None, src=src, bem=bem, n_jobs=n_jobs) filters = make_lcmv(raw_filt.info, fwd, data_cov, reg=0.05, pick_ori='max-power', weight_norm='nai', reduce_rank=True) t0 = time.time() stc = apply_lcmv_raw(raw_filt, filters) print(' Time: %s mns' % round((time.time() - t0) / 60, 2)) # Save result in stc files stc.save(op.join(datapath, subject, 'lcmv-vol')) stc.crop(0.0, 1.0) # plot dSPM time course in src space kwargs = dict(color='c', linestyle='--', linewidth=.5) f, ax = plt.subplots(1, 1, figsize=(8, 11)) mx = np.argmax(stc.data, axis=0) ax.plot(stc.times, stc.data[mx[:100], :].T) ax.autoscale(enable=True, axis='x', tight=True) ax.grid(True, which='major', axis='y', **kwargs) ax.set_xlabel('time (s)') ax.set_ylabel('strength')
def run_correlation(subjects_dir, subject, volume_spacing, freq): num_threads(8) frequency = str(freq) DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files') eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz' eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz' fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif' t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz') heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz' fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd-label.fif.gz' src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src-label.fif.gz' cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}-label.fif.gz' raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}-label.fif.gz' raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj-label.fif.gz' source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl' freesurfer_label = f'{DATA_DIR}/{subject}_freesurferlabel_{volume_spacing}-label.pkl' corr_true_file_label = f'{DATA_DIR}/{subject}_corr_ortho_true_{volume_spacing}_{frequency}_label.npy' check_for_files = [] check_for_files.append(corr_true_file_label) file_exist = [f for f in check_for_files if os.path.isfile(f)] file_not_exist = list(set(file_exist) ^ set(check_for_files)) if not file_not_exist: print('correlation files exists...') else: trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration file_trans = pathlib.Path(trans) file_ss = pathlib.Path(src_fname) file_fm = pathlib.Path(fwd_fname) file_proj = pathlib.Path(raw_proj) file_cov = pathlib.Path(cov_fname) file_rawcov = pathlib.Path(raw_cov_fname) t1 = nib.load(t1_fname) if not file_trans.exists(): print (f'{trans} File doesnt exist...') sys.exit(0) info = mne.io.read_info(fname_meg) # plot_registration(info, trans, subject, subjects_dir) print(file_ss) if not file_ss.exists(): src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', volume_spacing=volume_spacing) src.save(src_fname, overwrite=True) src = mne.read_source_spaces(src_fname) #view_SS_brain(subject, subjects_dir, src) if not file_fm.exists(): forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname) fwd = mne.read_forward_solution(fwd_fname) # sensitivty_plot(subject, subjects_dir, fwd) raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True) srate = raw.info['sfreq'] n_time_samps = raw.n_times time_secs = raw.times ch_names = raw.ch_names n_chan = len(ch_names) freq_res = srate/n_time_samps print('\n') print('-------------------------- Data summary-------------------------------') print(f'Subject {subject}') print(f"Frequency resolution {freq_res} Hz") print(f"The first few channel names are {ch_names[:3]}") print(f"The last time sample at {time_secs[-1]} seconds.") print(f"Sampling Frequency (No of time points/sec) {srate} Hz") print(f"Miscellaneous acquisition info {raw.info['description']}") print(f"Bad channels marked during data acquisition {raw.info['bads']}") print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.") print('------------------------------------------------------------------------') print('\n') # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True) if not file_proj.exists(): projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063') projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061') projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062') if projs_ecg is not None: mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors raw.info['projs'] += projs_ecg if projs_eog1 is not None: mne.write_proj(eye_proj1, projs_eog1) raw.info['projs'] += projs_eog1 if projs_eog2 is not None: mne.write_proj(eye_proj2, projs_eog2) raw.info['projs'] += projs_eog2 raw.apply_proj() raw.save(raw_proj, proj=True, overwrite=True) print(raw_proj) raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True) print(f'High-pass filtering data at 0.5 Hz') raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir') if not file_cov.exists(): cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest mne.write_cov(cov_fname, cov) cov = mne.read_cov(cov_fname) # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False # raw_proj_applied.crop(tmax=10) do_epochs = False l_freq = freq-2.0 h_freq = freq+2.0 print(f'Band pass filter data [{l_freq}, {h_freq}]') raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq) if do_epochs: print('Segmenting raw data...') events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.) raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5., baseline=None, preload=True) data_cov = mne.compute_covariance(raw_proj_filtered) else: if not file_rawcov.exists(): data_cov = mne.compute_raw_covariance(raw_proj_filtered) mne.write_cov(raw_cov_fname, data_cov) else: data_cov = mne.read_cov(file_rawcov) filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert() if do_epochs: stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False) else: stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True) print('Extracting label time course...') atlas = f'{subjects_dir}/{subject}/mri/aparc.a2009s+aseg.mgz' label_ts = mne.extract_label_time_course(stcs, atlas, fwd['src'], return_generator=False) label_ts = [label_ts] # Power Envelope Correlation print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize True') all_corr = envelope_correlation(label_ts, combine=None, orthogonalize="pairwise", log=True, absolute=True, verbose=None) print(f'Correlation saved to {corr_true_file_label}') np.save(corr_true_file_label, all_corr) del stcs
def test_make_lcmv(tmpdir, reg, proj): """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(proj=proj) for fwd in [forward, forward_vol]: filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov) stc = apply_lcmv(evoked, filters, 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 0.09 < tmax < 0.12, tmax assert 0.9 < np.max(max_stc) < 3., np.max(max_stc) if fwd is forward: # Test picking normal orientation (surface source space only). filters = make_lcmv(evoked.info, forward_surf_ori, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='normal', weight_norm=None) stc_normal = apply_lcmv(evoked, filters, 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)] lower = 0.04 if proj else 0.025 assert lower < tmax < 0.13, tmax lower = 3e-7 if proj else 2e-7 assert lower < np.max(max_stc) < 5e-7, np.max(max_stc) # No weight normalization was applied, so the amplitude of normal # orientation results should always be smaller than free # orientation results. assert (np.abs(stc_normal.data) <= stc.data).all() # Test picking source orientation maximizing output source power filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='max-power') stc_max_power = apply_lcmv(evoked, filters, 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)] lower = 0.08 if proj else 0.04 assert lower < tmax < 0.12, tmax assert 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_array_less(np.abs(mean_stc - mean_stc_max_pow), 0.6) # Test NAI weight normalization: filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg, noise_cov=noise_cov, pick_ori='max-power', weight_norm='nai') stc_nai = apply_lcmv(evoked, filters, 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 if not reducing rank with pytest.raises(ValueError): # Singular matrix or complex spectrum make_lcmv( evoked.info, fwd_sphere, data_cov, reg=0.1, noise_cov=noise_cov, weight_norm='unit-noise-gain', pick_ori='max-power', reduce_rank=False, rank='full') # Now let's reduce it filters = make_lcmv(evoked.info, fwd_sphere, data_cov, reg=0.1, noise_cov=noise_cov, weight_norm='unit-noise-gain', pick_ori='max-power', reduce_rank=True) stc_sphere = apply_lcmv(evoked, filters, 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)] lower = 0.08 if proj else 0.04 assert lower < tmax < 0.15, tmax assert 0.4 < np.max(max_stc) < 2., np.max(max_stc) # Test if spatial filter contains src_type assert 'src_type' in filters # __repr__ assert len(evoked.ch_names) == 22 assert len(evoked.info['projs']) == (4 if proj else 0) assert len(evoked.info['bads']) == 2 rank = 17 if proj else 20 assert 'LCMV' in repr(filters) assert 'unknown subject' not in repr(filters) assert '484' in repr(filters) assert '20' in repr(filters) assert 'rank %s' % rank in repr(filters) # I/O fname = op.join(str(tmpdir), 'filters.h5') with pytest.warns(RuntimeWarning, match='-lcmv.h5'): filters.save(fname) filters_read = read_beamformer(fname) assert isinstance(filters, Beamformer) assert isinstance(filters_read, Beamformer) # deal with object_diff strictness filters_read['rank'] = int(filters_read['rank']) filters['rank'] = int(filters['rank']) assert object_diff(filters, filters_read) == '' # Test if fixed forward operator is detected when picking normal or # max-power orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='max-power') # Test if non-surface oriented forward operator is detected when picking # normal orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') # Test if volume forward operator is detected when picking normal # orientation pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov, reg=0.01, noise_cov=noise_cov, pick_ori='normal') # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov=data_cov, reg=0.01, noise_cov=None, pick_ori='max-power') # 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) pytest.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 # also test here that no warnings are thrown - implemented to check whether # src should not be None warning occurs with pytest.warns(None) as w: stc = apply_lcmv(evoked, filters, max_ori_out='signed') assert len(w) == 0 # 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 if proj: raw_proj = deepcopy(raw) raw_proj.del_proj() with pytest.raises(ValueError, match='do not match the projections'): 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' pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol, data_cov, noise_cov=noise_cov, pick_ori=None, weight_norm='nai', reduce_rank=True) pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_surf_ori, data_cov, noise_cov=noise_cov, pick_ori='normal', weight_norm='nai', reduce_rank=True) # Test if spatial filter contains src_type assert 'src_type' in filters # check whether a filters object without src_type throws expected warning del filters['src_type'] # emulate 0.16 behaviour to cause warning with pytest.warns(RuntimeWarning, match='spatial filter does not contain ' 'src_type'): apply_lcmv(evoked, filters, max_ori_out='signed') # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov) stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed') stcs_ = apply_lcmv_epochs(epochs, filters, return_generator=True, max_ori_out='signed') assert_array_equal(stcs[0].data, next(stcs_).data) epochs.drop_bad() assert (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 filters = make_lcmv(evoked.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov) stc_fixed = apply_lcmv(evoked, filters, 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 filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01, noise_cov=noise_cov, label=label) stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed') assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data) # Test condition where the filters weights are zero. There should not be # any divide-by-zero errors zero_cov = data_cov.copy() zero_cov['data'][:] = 0 filters = make_lcmv(epochs.info, forward_fixed, zero_cov, reg=0.01, noise_cov=noise_cov) assert_array_equal(filters['weights'], 0)