fname = out_dir + '%s_%s_LCMV_blank_clean' % (subj, conds[c]) stc.save(fname) stc = lcmv(evoked_ds[c], forward, cov_base, data_cov, reg=0.01, pick_ori='max-power') stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to, morph_mat) fname = out_dir + '%s_%s_LCMV_base_clean' % (subj, conds[c]) stc.save(fname) # finally, compute DICS per band for band in bands: data_csd = compute_epochs_csd(epochs[conds[c]], mode='multitaper', tmin=tmin, tmax=tmax + btmax, fmin=band[0], fmax=band[1]) noise_csd = compute_epochs_csd(epochs[conds[c]], mode='multitaper', tmin=btmin, tmax=btmax, fmin=band[0], fmax=band[1]) stc = dics(evoked[c], forward, noise_csd, data_csd) stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to, morph_mat) stc.resample(20) fname = out_dir + '%s_%s_DICSevoked_%dto%d_clean' % (subj, conds[c], band[0], band[1]) stc.save(fname) stc = dics_source_power(epochs.info, forward, noise_csd, data_csd) stc = mne.morph_data_precomputed(subj, 'fsaverage', stc, vertices_to, morph_mat) fname = out_dir + '%s_%s_DICSepochs_%dto%d_clean' % (subj, conds[c], band[0], band[1]) stc.save(fname)
# Read forward operator forward = mne.read_forward_solution(fname_fwd) # Computing the data and noise cross-spectral density matrices # The time-frequency window was chosen on the basis of spectrograms from # example time_frequency/plot_time_frequency.py data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.04, tmax=0.15, fmin=6, fmax=10) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=0.0, fmin=6, fmax=10) evoked = epochs.average() # Compute DICS spatial filter and estimate source time courses on evoked data stc = dics(evoked, forward, noise_csd, data_csd, reg=0.05) plt.figure() ts_show = -30 # show the 40 largest responses plt.plot(1e3 * stc.times, stc.data[np.argsort(stc.data.max(axis=1))[ts_show:]].T) plt.xlabel('Time (ms)') plt.ylabel('DICS value') plt.title('DICS time course of the 30 largest sources.') plt.show() # Plot brain in 3D with PySurfer if available brain = stc.plot(hemi='rh', subjects_dir=subjects_dir, initial_time=0.1, time_unit='s') brain.show_view('lateral')
mode='multitaper', tmin=0.04, tmax=0.15, fmin=6, fmax=10) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=0.0, fmin=6, fmax=10) evoked = epochs.average() # Compute DICS spatial filter and estimate source time courses on evoked data stc = dics(evoked, forward, noise_csd, data_csd, reg=0.05) plt.figure() ts_show = -30 # show the 40 largest responses plt.plot(1e3 * stc.times, stc.data[np.argsort(stc.data.max(axis=1))[ts_show:]].T) plt.xlabel('Time (ms)') plt.ylabel('DICS value') plt.title('DICS time course of the 30 largest sources.') plt.show() # Plot brain in 3D with PySurfer if available brain = stc.plot(hemi='rh', subjects_dir=subjects_dir, initial_time=0.1, time_unit='s')
def test_dics(): """Test DICS with evoked data and single trials """ raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() stc = dics(evoked, forward, noise_csd=noise_csd, data_csd=data_csd, label=label) stc.crop(0, None) 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)] # Incorrect due to limited number of epochs assert_true(0.04 < tmax < 0.05) assert_true(10 < np.max(max_stc) < 13) # Test picking normal orientation stc_normal = dics(evoked, forward_surf_ori, noise_csd, data_csd, pick_ori="normal", label=label) stc_normal.crop(0, None) # 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 if fixed forward operator is detected when picking normal # orientation assert_raises(ValueError, dics_epochs, epochs, forward_fixed, noise_csd, data_csd, pick_ori="normal") # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, dics_epochs, epochs, forward, noise_csd, data_csd, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, dics_epochs, epochs, forward_vol, noise_csd, data_csd, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, reg=0.01, label=label) # Testing returning of generator stcs_ = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, reg=0.01, return_generator=True, label=label) assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) # Test whether correct number of trials was returned epochs.drop_bad() 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.crop(0, None).data stc_avg /= len(stcs) idx = np.argmax(np.max(stc_avg, axis=1)) max_stc = stc_avg[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.045 < tmax < 0.06) # incorrect due to limited # of epochs assert_true(12 < np.max(max_stc) < 18.5)
def test_dics(): """Test DICS with evoked data and single trials """ raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() stc = dics(evoked, forward, noise_csd=noise_csd, data_csd=data_csd, label=label) stc.crop(0, None) 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)] # Incorrect due to limited number of epochs assert_true(0.04 < tmax < 0.05) assert_true(10 < np.max(max_stc) < 13) # Test picking normal orientation stc_normal = dics(evoked, forward_surf_ori, noise_csd, data_csd, pick_ori="normal", label=label) stc_normal.crop(0, None) # 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 if fixed forward operator is detected when picking normal # orientation assert_raises(ValueError, dics_epochs, epochs, forward_fixed, noise_csd, data_csd, pick_ori="normal") # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, dics_epochs, epochs, forward, noise_csd, data_csd, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, dics_epochs, epochs, forward_vol, noise_csd, data_csd, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, reg=0.01, label=label) # Testing returning of generator stcs_ = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, reg=0.01, return_generator=True, label=label) assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) # Test whether correct number of trials was returned 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.crop(0, None).data stc_avg /= len(stcs) idx = np.argmax(np.max(stc_avg, axis=1)) max_stc = stc_avg[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.045 < tmax < 0.06) # incorrect due to limited # of epochs assert_true(12 < np.max(max_stc) < 18.5)
##40 hz####################################################### data_csd40 = csd_epochs(epochs40, mode='multitaper', tmin=0.01, tmax=0.50, fmin=35, fmax=45) noise_csd40 = csd_epochs(epochs40, mode='multitaper', tmin=-0.49, tmax=0.00, fmin=35, fmax=45) stc40_2 = dics_source_power(epochs40.info, fwd40, noise_csd40, data_csd40) # Compute DICS spatial filter and estimate source power stc40_3 = dics(evoked40, fwd40, noise_csd40, data_csd40, reg=0.05) stc40_2.save(stc40_fname2, ftype='stc') stc40_3.save(stc40_fname3, ftype='stc') ################################################################ ####30 hz####################################################### data_csd30 = csd_epochs(epochs30, mode='multitaper', tmin=0.01, tmax=0.50, fmin=25, fmax=35) noise_csd30 = csd_epochs(epochs30, mode='multitaper', tmin=-0.49, tmax=0.00,
mode='multitaper', tmin=0.04, tmax=0.15, fmin=6, fmax=10) noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=-0.11, tmax=0.0, fmin=6, fmax=10) evoked = epochs.average() # Compute DICS spatial filter and estimate source time courses on evoked data stc = dics(evoked, forward, noise_csd, data_csd) plt.figure() ts_show = -30 # show the 40 largest responses plt.plot(1e3 * stc.times, stc.data[np.argsort(stc.data.max(axis=1))[ts_show:]].T) plt.xlabel('Time (ms)') plt.ylabel('DICS value') plt.title('DICS time course of the 30 largest sources.') plt.show() # Plot brain in 3D with PySurfer if available brain = stc.plot(hemi='rh', subjects_dir=subjects_dir) brain.set_data_time_index(180) brain.show_view('lateral')
def DICS_inverse(fn_epo, event_id=1,event='LLst', ctmin=0.05, ctmax=0.25, fmin=4, fmax=8, min_subject='fsaverage'): """ Inverse evokes into source space using DICS method. ---------- fn_epo : epochs of raw data. event_id: event id related with epochs. ctmin: the min time for computing CSD ctmax: the max time for computing CSD fmin: min value of the interest frequency band fmax: max value of the interest frequency band min_subject: the subject for the common brain space. save_forward: Whether save the forward solution or not. """ from mne import Epochs, pick_types from mne.io import Raw from mne.event import make_fixed_length_events fnlist = get_files_from_list(fn_epo) # loop across all filenames for fname in fnlist: meg_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-epo.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = meg_path + '/%s-trans.fif' % subject fn_src = subject_path + '/bem/%s-ico-5-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject # Make sure the target path is exist stc_path = min_dir + '/DICS_ROIs/%s' % subject set_directory(stc_path) # Read the MNI source space epochs = mne.read_epochs(fname) tmin = epochs.times.min() tmax = epochs.times.max() fn_empty = meg_path + '/%s_empty,nr-raw.fif' % subject raw_noise = Raw(fn_empty, preload=True) epochs.info['bads'] = raw_noise.info['bads'] picks_noise = pick_types(raw_noise.info, meg='mag', exclude='bads') events_noise = make_fixed_length_events(raw_noise, event_id, duration=1.) epochs_noise = Epochs(raw_noise, events_noise, event_id, tmin, tmax, proj=True, picks=picks_noise, baseline=None, preload=True, reject=None) # Make sure the number of noise epochs is the same as data epochs epochs_noise = epochs_noise[:len(epochs.events)] evoked = epochs.average() forward = mne.make_forward_solution(epochs.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) forward = mne.convert_forward_solution(forward, surf_ori=True) from mne.time_frequency import compute_epochs_csd from mne.beamformer import dics data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) noise_csd = compute_epochs_csd(epochs_noise, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) stc = dics(evoked, forward, noise_csd, data_csd) from mne import morph_data stc_morph = morph_data(subject, min_subject, stc, grade=5, smooth=5) stc_morph.save(stc_path + '/%s_%d_%d' % (event, fmin, fmax), ftype='stc')
def estimate_beamformer(epochs, fname_forward_sol, noise_cov_mat=None, method="DICS", show=True): """"Estimates source localization for the given data set using beamformer.""" # read forward operator forward_sol = mne.read_forward_solution(fname_forward_sol, surf_ori=True) if method == "DICS": print ">>>> performing source localization using DICS beamformer..." # Computing the data and noise cross-spectral density matrices data_csds = compute_epochs_csd(epochs, mode='fourier', tmin=0.04, tmax=0.15, fmin=5, fmax=20) noise_csds = compute_epochs_csd(epochs, mode='fourier', tmin=-0.11, tmax=-0.0, fmin=5, fmax=20) pdb.set_trace() # Compute DICS spatial filter and estimate source power src_loc = beam.dics(epochs.average(), forward_sol, noise_csds, data_csds) # for showing results fmin = 0.5; fmid = 3.0; fmax = 5.0 else: print ">>>> performing source localization using LCMV beamformer..." if noise_cov_mat is None: print "To use LCMV beamformer the noise-covariance matrix keyword must be set." sys.exit() evoked = epochs.average() noise_cov_mat = mne.cov.regularize(noise_cov_mat, evoked.info, mag=0.05, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) src_loc = beam.lcmv(evoked, forward_sol, noise_cov_mat, data_cov, reg=0.01, pick_ori=None) # for showing results fmin = 0.01; fmid = 0.5; fmax = 1.0 # show results if desired if show is not None: subjects_dir = os.environ.get('SUBJECTS_DIR') brain = src_loc.plot(surface='inflated', hemi='both', subjects_dir=subjects_dir, config_opts={'cortex':'bone'}, time_viewer=True, fmin=fmin, fmid=fmid, fmax=fmax)
def test_dics(): """Test DICS with evoked data and single trials.""" raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol = _get_data() epochs.crop(0, None) reg = 0.5 # Heavily regularize due to low SNR for real_filter in (True, False): stc = dics(evoked, forward, noise_csd=noise_csd, data_csd=data_csd, label=label, real_filter=real_filter, reg=reg) 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)] # Incorrect due to limited number of epochs assert 0.04 < tmax < 0.06 assert 3. < np.max(max_stc) < 6. # Test picking normal orientation stc_normal = dics(evoked, forward_surf_ori, noise_csd, data_csd, pick_ori="normal", label=label, real_filter=True, reg=reg) assert stc_normal.data.min() < 0 # this doesn't take abs stc_normal = dics(evoked, forward_surf_ori, noise_csd, data_csd, pick_ori="normal", label=label, reg=reg) assert stc_normal.data.min() >= 0 # this does take abs # The amplitude of normal orientation results should always be smaller than # free orientation results assert (np.abs(stc_normal.data) <= stc.data).all() # Test if fixed forward operator is detected when picking normal # orientation raises(ValueError, dics_epochs, epochs, forward_fixed, noise_csd, data_csd, pick_ori="normal") # Test if non-surface oriented forward operator is detected when picking # normal orientation raises(ValueError, dics_epochs, epochs, forward, noise_csd, data_csd, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation raises(ValueError, dics_epochs, epochs, forward_vol, noise_csd, data_csd, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, label=label) # Testing returning of generator stcs_ = dics_epochs(epochs, forward_fixed, noise_csd, data_csd, return_generator=True, label=label) assert_array_equal(stcs[0].data, advance_iterator(stcs_).data) # Test whether correct number of trials was returned epochs.drop_bad() assert 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) idx = np.argmax(np.max(stc_avg, axis=1)) max_stc = stc_avg[idx] tmax = stc.times[np.argmax(max_stc)] assert 0.120 < tmax < 0.150 # incorrect due to limited # assert 12 < np.max(max_stc) < 18.5
def apply_inverse(fn_epo, event='LLst',ctmin=0.05, ctmax=0.25, nctmin=-0.2, nctmax=0, fmin=4, fmax=8, min_subject='fsaverage', STCs=False): """ Inverse evokes into source space using DICS method. ---------- fn_epo : epochs of raw data. event_id: event id related with epochs. ctmin: the min time for computing CSD ctmax: the max time for computing CSD fmin: min value of the interest frequency band fmax: max value of the interest frequency band min_subject: the subject for the common brain space. STCs: bool, make STCs of epochs. """ from mne import Epochs, pick_types from mne.io import Raw from mne.event import make_fixed_length_events fnlist = get_files_from_list(fn_epo) # loop across all filenames for fname in fnlist: subjects_dir = os.environ['SUBJECTS_DIR'] # extract the subject infromation from the file name meg_path = os.path.split(fname)[0] name = os.path.basename(fname) stc_name = name[:name.rfind('-epo.fif')] subject = name.split('_')[0] subject_path = subjects_dir + '/%s' %subject min_dir = subjects_dir + '/%s' %min_subject fn_trans = meg_path + '/%s-trans.fif' % subject fn_src = subject_path + '/bem/%s-ico-4-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject # Make sure the target path is exist stc_path = min_dir + '/DICS_ROIs/%s' % subject set_directory(stc_path) # Read the MNI source space epochs = mne.read_epochs(fname) evoked = epochs.average() forward = mne.make_forward_solution(epochs.info, trans=fn_trans, src=fn_src, bem=fn_bem, fname=None, meg=True, eeg=False, mindist=5.0, n_jobs=2, overwrite=True) forward = mne.convert_forward_solution(forward, surf_ori=True) from mne.time_frequency import compute_epochs_csd from mne.beamformer import dics data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=ctmin, tmax=ctmax, fmin=fmin, fmax=fmax) noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=nctmin, tmax=nctmax, fmin=fmin, fmax=fmax) stc = dics(evoked, forward, noise_csd, data_csd) from mne import morph_data stc_morph = morph_data(subject, min_subject, stc, grade=4, smooth=4) stc_morph.save(stc_path + '/%s_%d_%d' % (stc_name, fmin, fmax), ftype='stc') if STCs == True: stcs_path = stc_path + '/STCs-%s/' %event reset_directory(stcs_path) stcs = dics(epochs, forward, noise_csd, data_csd) s = 0 while s < len(stcs): stc_morph = mne.morph_data(subject, min_subject, stcs[s], grade=4, smooth=4) stc_morph.save(stcs_path + '/trial_%s' % (str(s)), ftype='stc') s = s + 1
def estimate_beamformer(epochs, fname_forward_sol, noise_cov_mat=None, method="DICS", show=True): """"Estimates source localization for the given data set using beamformer.""" # read forward operator forward_sol = mne.read_forward_solution(fname_forward_sol, surf_ori=True) if method == "DICS": print ">>>> performing source localization using DICS beamformer..." # Computing the data and noise cross-spectral density matrices data_csds = compute_epochs_csd(epochs, mode='fourier', tmin=0.04, tmax=0.15, fmin=5, fmax=20) noise_csds = compute_epochs_csd(epochs, mode='fourier', tmin=-0.11, tmax=-0.0, fmin=5, fmax=20) pdb.set_trace() # Compute DICS spatial filter and estimate source power src_loc = beam.dics(epochs.average(), forward_sol, noise_csds, data_csds) # for showing results fmin = 0.5 fmid = 3.0 fmax = 5.0 else: print ">>>> performing source localization using LCMV beamformer..." if noise_cov_mat is None: print "To use LCMV beamformer the noise-covariance matrix keyword must be set." sys.exit() evoked = epochs.average() noise_cov_mat = mne.cov.regularize(noise_cov_mat, evoked.info, mag=0.05, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) src_loc = beam.lcmv(evoked, forward_sol, noise_cov_mat, data_cov, reg=0.01, pick_ori=None) # for showing results fmin = 0.01 fmid = 0.5 fmax = 1.0 # show results if desired if show is not None: subjects_dir = os.environ.get('SUBJECTS_DIR') brain = src_loc.plot(surface='inflated', hemi='both', subjects_dir=subjects_dir, config_opts={'cortex': 'bone'}, time_viewer=True, fmin=fmin, fmid=fmid, fmax=fmax)