reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6)) # define frequencies of interest fmin, fmax = 0., 70. bandwidth = 4. # bandwidth of the windows in Hz # compute source space psd in label # Note: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. stcs = compute_source_psd_epochs(epochs, inverse_operator, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, return_generator=True) # compute average PSD over the first 10 epochs n_epochs = 10 for i, stc in enumerate(stcs): if i >= n_epochs: break if i == 0: psd_avg = np.mean(stc.data, axis=0) else: psd_avg += np.mean(stc.data, axis=0)
# use_fft=False, # n_jobs=4, # decim=2, # baseline=(-1, 0), # ) epochs_active = epochs.copy().crop(tmin=cfg.config_sources["active_win"][0], tmax=cfg.config_sources["active_win"][1]) epochs_base = epochs.copy().crop( tmin=cfg.config_sources["baseline_win"][0], tmax=cfg.config_sources["baseline_win"][1], ) stcs_low_act = compute_source_psd_epochs(epochs_active["low"], inverse_operator, fmin=2, fmax=30, lambda2=2) stcs_high_act = compute_source_psd_epochs(epochs_active["high"], inverse_operator, fmin=2, fmax=30, lambda2=2) stcs_low_base = compute_source_psd_epochs(epochs_base["low"], inverse_operator, fmin=2, fmax=30, lambda2=2)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6)) # define frequencies of interest fmin, fmax = 0., 70. bandwidth = 4. # bandwidth of the windows in Hz # compute source space psd in label # Note: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. stcs = compute_source_psd_epochs(epochs, inverse_operator, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, label=label, return_generator=True) # compute average PSD over the first 10 epochs n_epochs = 10 for i, stc in enumerate(stcs): if i >= n_epochs: break if i == 0: psd_avg = np.mean(stc.data, axis=0) else: psd_avg += np.mean(stc.data, axis=0) psd_avg /= n_epochs freqs = stc.times # the frequencies are stored here
label_lh = labels[6] + labels[8] + labels[10] label_rh = labels[7] + labels[9] + labels[11] # labels = mne.read_labels_from_annot( # subject, # parc='PALS_B12_Lobes', # # regexp="Bro", # subjects_dir=subjects_dir) # label_lh, label_rh = labels[9], labels[10] # Compute inverse solution # stc = apply_inverse(evoked, inv, lambda2, method, # pick_ori='normal') epochs.crop(tmin=tmin, tmax=tmax) stc = compute_source_psd_epochs(epochs, inv, fmin=8, fmax=12, bandwidth=1) # Make an STC in the time interval of interest and take the mean mean_data = np.mean(np.asarray([s.data for s in stc]), axis=0) stc_mean = mne.SourceEstimate( mean_data, stc[0].vertices, tmin=stc[0].tmin, tstep=stc[0].tstep) # use the stc_mean to generate a functional label # region growing is halted at 60% of the peak value within the # anatomical label / ROI specified by aparc_label_name # calc lh label stc_mean_label = stc_mean.in_label(label_lh) data = np.abs(stc_mean_label.data) stc_mean_label.data[data < 0.7 * np.max(data)] = 0.
loose=0.2, depth=0.8, verbose=True) method = "sLORETA" snr = 3. lambda2 = 1. / snr**2 bandwidth = 'hann' #for fast csp n_epochs_use = fast_epo.events.shape[0] stcs_fast = compute_source_psd_epochs(fast_epo[:n_epochs_use], inverse_operator_fast, lambda2=lambda2, method=method, fmin=10, fmax=17, bandwidth=bandwidth, return_generator=True, verbose=True) psd_avg = 0. for i, stc_fast in enumerate(stcs_fast): psd_avg += stc_fast.data psd_avg /= n_epochs_use freqs = stc_fast.times # the frequencies are stored here stc_fast.data = psd_avg #for slow csp n_epochs_use = slow_epo.events.shape[0] stcs_slow = compute_source_psd_epochs(slow_epo[:n_epochs_use], inverse_operator_slow,
verbose=True) #stc calculation method = "sLORETA" snr = 3. #lambda2 = 0.05 lambda2 = 1. / snr**2 bandwidth = 'hann' #for slow interstimulus epochs n_epochs_use = slow_epo_isi.events.shape[0] stcs_slow_isi = compute_source_psd_epochs(slow_epo_isi[:n_epochs_use], inverse_operator, lambda2=lambda2, method=method, fmin=2, fmax=40, bandwidth=bandwidth, return_generator=True, verbose=True) psd_avg = 0. for i, stc_slow_isi in enumerate(stcs_slow_isi): psd_avg += stc_slow_isi.data psd_avg /= n_epochs_use freqs = stc_slow_isi.times stc_slow_isi.data = psd_avg #for medium interstimulus epochs n_epochs_use = medium_epo_isi.events.shape[0] stcs_medium_isi = compute_source_psd_epochs(medium_epo_isi[:n_epochs_use], inverse_operator,
def intra(subj): """ Performs initial computations within subject and returns average PSD and variance of all epochs. """ print ("Now beginning intra processing on " + subj + "...\n") * 5 # Set function parameters fname_label = subjects_dir + "/" + subj + "/" + "label/%s.label" % label_name fname_raw = data_path + subj + "/" + subj + "_list" + list_num + "_raw_sss-ico-4-fwd.fif" if os.path.isfile(data_path + subj + "/" + subj + "_list" + list_num + "_raw_sss-ico-4-fwd.fif"): fname_fwd = data_path + subj + "/" + subj + "_list" + list_num + "_raw_sss-ico-4-fwd.fif" else: print ("Subject " + subj + " does not have a ico-4-fwd.fif on file.") if label_name.startswith("lh."): hemi = "left" elif label_name.startswith("rh."): hemi = "right" # Load data label = mne.read_label(fname_label) raw = fiff.Raw(fname_raw) forward_meg = mne.read_forward_solution(fname_fwd) # Estimate noise covariance from the raw data. precov = mne.compute_raw_data_covariance(raw, reject=dict(eog=150e-6)) write_cov(data_path + subj + "/" + subj + "-cov.fif", precov) # Find events from raw file events = mne.find_events(raw, stim_channel="STI 014") # Set up pick list: (MEG minus bad channels) include = [] exclude = raw.info["bads"] picks = fiff.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, include=include, exclude=exclude) # Read epochs and remove bad 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), ) # Average epochs and get an evoked dataset. Save to disk. evoked = epochs.average() evoked.save(data_path + subj + "/" + subj + "_list" + list_num + "_rest_raw_sss-ave.fif") # Regularize noise cov cov = mne.cov.regularize(precov, evoked.info, grad=4000e-13, mag=4e-12, eog=150e-6, proj=True) # Make inverse operator info = evoked.info inverse_operator = make_inverse_operator(info, forward_meg, cov, loose=None, depth=0.8) # Pull data for averaging later epc_array = epochs.get_data() # Compute the inverse solution inv = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, label=label) # Need to add a line here to automatically create stc directory within subj epoch_num = 1 epoch_num_str = str(epoch_num) for i in inv: i.save(data_path + subj + "/tmp/" + label_name[3:] + "_rest_raw_sss-ico-4-inv" + epoch_num_str) epoch_num = epoch_num + 1 epoch_num_str = str(epoch_num) # The following is used to remove the empty opposing hemisphere files # and then move the files to save into the appropriate directory if hemi == "left": filelist = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-rh.stc")] for f in filelist: os.remove(data_path + subj + "/tmp/" + f) keepers = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-lh.stc")] for f in keepers: src = f os.rename(data_path + subj + "/tmp/" + src, data_path + subj + "/inv/" + src) elif hemi == "right": filelist = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-lh.stc")] for f in filelist: os.remove(data_path + subj + "/tmp/" + f) keepers = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-rh.stc")] for f in keepers: src = f os.rename(data_path + subj + "/tmp/" + src, data_path + subj + "/inv/" + src) # define frequencies of interest bandwidth = 4.0 # bandwidth of the windows in Hz # compute source space psd in label # Note: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. psd = compute_source_psd_epochs( epochs, inverse_operator, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, label=label, return_generator=False, ) epoch_num = 1 epoch_num_str = str(epoch_num) for i in psd: i.save(data_path + subj + "/" + "tmp" + "/" + label_name[3:] + "_dspm_snr-1_PSD" + epoch_num_str) epoch_num = epoch_num + 1 epoch_num_str = str(epoch_num) if hemi == "left": filelist = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-rh.stc")] for f in filelist: os.remove(data_path + subj + "/tmp/" + f) keepers = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-lh.stc")] for f in keepers: src = f os.rename(data_path + subj + "/tmp/" + src, data_path + subj + "/psd/" + src) elif hemi == "right": filelist = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-lh.stc")] for f in filelist: os.remove(data_path + subj + "/tmp/" + f) keepers = [f for f in os.listdir(data_path + subj + "/tmp") if f.endswith("-rh.stc")] for f in keepers: src = f os.rename(data_path + subj + "/tmp/" + src, data_path + subj + "/psd/" + src) # This code computes the average PSDs of each epoch. Each PSD file is an array of shape N_vertices*N_frequencies. This code averages the PSD value of each vertex together and outputs the average PSD value of each frequency. Then, it averages the PSD values of each epoch, outputting one average PSD value per frequency value, i.e., this is the average across epochs. n_epochs = len(epc_array) for i, stc in enumerate(psd): if i >= n_epochs: break if i == 0: psd_avg = np.mean(stc.data, axis=0) else: psd_avg += np.mean(stc.data, axis=0) print ("Length of psd for subject " + subj + " is " + str(len(psd)) + ".") print ("Number of epochs for subject " + subj + " is " + str(n_epochs) + ".") if len(psd) != 0: psd_avg /= n_epochs # Compute variance for each epoch and then variance across epochs n_epochs = len(epc_array) for i, stc in enumerate(psd): if i >= n_epochs: psd_var = np.array() break if i == 0: psd_var = np.var(stc.data, axis=0) else: psd_var = np.vstack((psd_var, np.var(stc.data, axis=0))) if len(psd) >= 2: tot_var = np.var(psd_var, axis=0) if len(psd) <= 1: failed_subj = subj print (failed_subj + " failed. No PSD values calculated, likely because all epochs were rejected.") return failed_subj, failed_subj, failed_subj if len(psd) >= 2: return (psd_avg, tot_var, len(psd_avg))
for condition in conditions: # Load data inv = read_inverse_operator(mne_folder + "%s_%s-inv.fif" % (subject, condition)) epochs = mne.read_epochs(epochs_folder + "%s_%s-epo.fif" % (subject, condition)) # define frequencies of interest fmin, fmax = 0., 90. bandwidth = 2. # bandwidth of the windows in Hz # compute source space psd in label # Note: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. epochs.crop(-2.75, -2.35) stcs = compute_source_psd_epochs( epochs, inv, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, return_generator=False) pickle.dump(stcs, open(source_folder + "%s_%s_psd_pre_epo.pkl" % (subject, condition), 'wb'))
# define frequencies of interest fmin, fmax = 0., 70. bandwidth = 4. # bandwidth of the windows in Hz # %% # Compute source space PSD in label # --------------------------------- # # ..note:: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. n_epochs_use = 10 stcs = compute_source_psd_epochs(epochs[:n_epochs_use], inverse_operator, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, label=label, return_generator=True, verbose=True) # compute average PSD over the first 10 epochs psd_avg = 0. for i, stc in enumerate(stcs): psd_avg += stc.data psd_avg /= n_epochs_use freqs = stc.times # the frequencies are stored here stc.data = psd_avg # overwrite the last epoch's data with the average # %% # Visualize the 10 Hz PSD: brain = stc.plot(initial_time=10., hemi='lh', views='lat', # 10 HZ
# Read labels for V1 and MT v1_label = mne.read_label(datapath + 'Results_Alpha_and_Gamma/' + subject + '/' + subject + '_V1_rh.label') mt_label = mne.read_label(datapath + 'Results_Alpha_and_Gamma/' + subject + '/' + subject + '_MT_rh.label') #stc calculation method = "sLORETA" snr = 3. #lambda2 = 0.05 lambda2 = 1. / snr ** 2 bandwidth = 'hann' #for slow interstimulus epochs in v1 n_epochs_use = slow_epo_isi.events.shape[0] stcs_slow_isi_v1 = compute_source_psd_epochs(slow_epo_isi[:n_epochs_use], inverse_operator, lambda2=lambda2, method=method, fmin=2, fmax=40, bandwidth=bandwidth, label=v1_label, return_generator=True, verbose=True) psd_avg = 0. for i, stc_slow_isi_v1 in enumerate(stcs_slow_isi_v1): psd_avg += stc_slow_isi_v1.data psd_avg /= n_epochs_use freqs = stc_slow_isi_v1.times stc_slow_isi_v1.data = psd_avg #for fast interstimulus epochs in v1 n_epochs_use = fast_epo_isi.events.shape[0] stcs_fast_isi_v1 = compute_source_psd_epochs(fast_epo_isi[:n_epochs_use], inverse_operator, lambda2=lambda2, method=method, fmin=2, fmax=40, bandwidth=bandwidth, label=v1_label,
#for V1 method = "sLORETA" snr = 3. #lambda2 = 0.05 lambda2 = 1. / snr**2 bandwidth = 4.0 #for prestim epochs n_epochs_use = slow_epo_prestim.events.shape[0] stcs_slow_prestim = compute_source_psd_epochs( slow_epo_prestim[:n_epochs_use], inverse_operator, lambda2=lambda2, method=method, fmin=45, fmax=75, bandwidth=bandwidth, label=v1_label, return_generator=True, verbose=True) psd_avg = 0. for i, stc_slow_prestim in enumerate(stcs_slow_prestim): psd_avg += stc_slow_prestim.data psd_avg /= n_epochs_use freqs = stc_slow_prestim.times stc_slow_prestim.data = psd_avg #for stim epoch n_epochs_use = slow_epo_stim.events.shape[0] stcs_slow_stim = compute_source_psd_epochs(slow_epo_stim[:n_epochs_use],
def intra(subj): ''' Performs initial computations within subject and returns average PSD and variance of all epochs. ''' print('Now beginning intra processing on ' + subj + '...\n') * 5 # Set function parameters fname_label = subjects_dir + '/' + subj + '/' + 'label/%s.label' % label_name fname_raw = data_path + subj + '/' + subj + '_rest_raw_sss.fif' if os.path.isfile(data_path + subj + '/' + subj + '_rest_raw_sss-ico-4-fwd.fif'): fname_fwd = data_path + subj + '/' + subj + '_rest_raw_sss-ico-4-fwd.fif' else: print('Subject ' + subj + ' does not have a ico-4-fwd.fif on file.') if label_name.startswith('lh.'): hemi = 'left' elif label_name.startswith('rh.'): hemi = 'right' # Load data label = mne.read_label(fname_label) raw = fiff.Raw(fname_raw) forward_meg = mne.read_forward_solution(fname_fwd) # Estimate noise covariance from teh raw data cov = mne.compute_raw_data_covariance(raw, reject=dict(eog=150e-6)) write_cov(data_path + subj + '/' + subj + '-cov.fif', cov) # Make inverse operator info = raw.info inverse_operator = make_inverse_operator(info, forward_meg, cov, loose=None, depth=0.8) # Epoch data into 4s intervals events = mne.make_fixed_length_events(raw, 1, start=0, stop=None, duration=4.) # Set up pick list: (MEG minus bad channels) include = [] exclude = raw.info['bads'] picks = fiff.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, include=include, exclude=exclude) # Read epochs and remove bad 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)) # Pull data for averaging later epc_array = epochs.get_data() # Compute the inverse solution inv = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, label=label) #Need to add a line here to automatically create stc directory within subj epoch_num = 1 epoch_num_str = str(epoch_num) for i in inv: # i.save(data_path + subj + '/tmp/' + label_name[3:] + '_rest_raw_sss-oct-6-inv' + epoch_num_str) i.save(data_path + subj + '/tmp/' + label_name[3:] + '_rest_raw_sss-ico-4-inv' + epoch_num_str) epoch_num = epoch_num + 1 epoch_num_str = str(epoch_num) # The following is used to remove the empty opposing hemisphere files # and then move the files to save into the appropriate directory if hemi == 'left': filelist = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-rh.stc") ] for f in filelist: os.remove(data_path + subj + '/tmp/' + f) keepers = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-lh.stc") ] for f in keepers: src = f os.rename(data_path + subj + '/tmp/' + src, data_path + subj + '/inv/' + src) elif hemi == 'right': filelist = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-lh.stc") ] for f in filelist: os.remove(data_path + subj + '/tmp/' + f) keepers = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-rh.stc") ] for f in keepers: src = f os.rename(data_path + subj + '/tmp/' + src, data_path + subj + '/inv/' + src) # define frequencies of interest bandwidth = 4. # bandwidth of the windows in Hz # compute source space psd in label # Note: By using "return_generator=True" stcs will be a generator object # instead of a list. This allows us so to iterate without having to # keep everything in memory. psd = compute_source_psd_epochs(epochs, inverse_operator, lambda2=lambda2, method=method, fmin=fmin, fmax=fmax, bandwidth=bandwidth, label=label, return_generator=False) epoch_num = 1 epoch_num_str = str(epoch_num) for i in psd: i.save(data_path + subj + '/' + 'tmp' + '/' + label_name[3:] + '_dspm_snr-1_PSD'+ epoch_num_str) epoch_num = epoch_num + 1 epoch_num_str = str(epoch_num) if hemi == 'left': filelist = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-rh.stc") ] for f in filelist: os.remove(data_path + subj + '/tmp/' + f) keepers = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-lh.stc") ] for f in keepers: src = f os.rename(data_path + subj + '/tmp/' + src,data_path + subj + '/psd/' + src) elif hemi == 'right': filelist = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-lh.stc") ] for f in filelist: os.remove(data_path + subj + '/tmp/' + f) keepers = [ f for f in os.listdir(data_path + subj + '/tmp') if f.endswith("-rh.stc") ] for f in keepers: src = f os.rename(data_path + subj + '/tmp/' + src,data_path + subj + '/psd/' + src) # This code computes the average PSDs of each epoch. Each PSD file is an array of shape N_vertices*N_frequencies. This code averages the PSD value of each vertex together and outputs the average PSD value of each frequency. Then, it averages the PSD values of each epoch, outputting one average PSD value per frequency value, i.e., this is the average across epochs. n_epochs = len(epc_array) for i, stc in enumerate(psd): if i >= n_epochs: break if i == 0: psd_avg = np.mean(stc.data, axis=0) else: psd_avg += np.mean(stc.data, axis=0) print('Length of psd for subject ' + subj + ' is ' + str(len(psd)) + '.') print('Number of epochs for subject ' + subj + ' is ' + str(n_epochs) + '.') if len(psd) != 0: psd_avg /= n_epochs # Compute variance for each epoch and then variance across epochs n_epochs = len(epc_array) for i, stc in enumerate(psd): if i >= n_epochs: psd_var = np.array() break if i == 0: psd_var = np.var(stc.data, axis=0) else: psd_var = np.vstack((psd_var,np.var(stc.data, axis=0))) if len(psd) >= 2: tot_var = np.var(psd_var, axis=0) if len(psd) <= 1: failed_subj = subj print(failed_subj + ' failed. No PSD values calculated, likely because all epochs were rejected.') return failed_subj, failed_subj, failed_subj if len(psd) >= 2: return (psd_avg, tot_var, len(psd_avg))